<template>
  <div>
    <!-- <SearchCusinfo ref="SearchCusinfo" :parentObj="this"></SearchCusinfo> -->
    <a-drawer title="选择出库单" width="90%" placement="right" :visible="visible" @close="() => {
      this.visible = false;
    }
      " :body-style="{ paddingBottom: '80px' }">
      <div style="margin-bottom: 10px" class="table-page-search-wrapper">
        <h2>客户:{{ this.cusname }}</h2>
        <a-input style="width: 200px; margin-right: 8px" v-model="OutboundOrder" placeholder="出库单号" @keydown.enter="() => {
      this.pagination.current = 1;
      this.getDataList();
    }
      " />
        <a-select v-model="start" style="width: 100px; margin-left: 8px" @change="changeTime" name="radioGroup"
          :default-value="0">
          <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="index">
            {{ i }}
          </a-select-option>
        </a-select>
        <a-range-picker style="margin: 0 8px; width: 220px" :disabled="timeDisabled" v-model="time"
          valueFormat="YYYY-MM-DD" />
        <a-button type="primary" @click="() => {
      this.pagination.current = 1;
      this.getDataList();
    }
      ">查询</a-button>
      </div>
      <div>
        <a-table ref="table" :scroll="{ x: 800 }" :columns="columns" :rowKey="(row) => row.Id" :dataSource="data"
          :pagination="pagination" :loading="loading" @change="handleTableChange" :rowSelection="rowSelection1"
          :bordered="true" size="small">
          <span slot="action" slot-scope="text, record, index">
            <a @click="handlerpreviewTable(record.Id)">预览</a>
          </span>
          <span slot="MadeDate" slot-scope="text, record, index">
            <span>{{ text.slice(0,10) }}</span>
          </span>

        </a-table>
        <div>
          合计金额:
          <span>{{ PriceCount | NumberFormats }}</span>
        </div>
      </div>

      <!-- -- 开票信息 -->

      <div :style="{
      position: 'absolute',
      right: 0,
      bottom: 0,
      width: '100%',
      borderTop: '1px solid #e9e9e9',
      padding: '10px 16px',
      background: '#fff',
      textAlign: 'right',
      zIndex: 1,
    }">
        <a-button v-if="!cancel" :style="{ marginRight: '8px' }" @click="shouCusinfo">上一步</a-button>
        <a-button v-if="cancel" :style="{ marginRight: '8px' }" @click="() => {
      this.visible = false;
    }
      ">取消</a-button>
        <a-button type="primary" @click="handleSubmit">下一步</a-button>
      </div>
      <a-modal title="批量改价" :visible="changeVisible" @ok="handleChangePrice" @cancel="() => {
      this.changeVisible = false;
      this.changeMarkup = '';
    }
      ">
        <div>
          <span>加成率：</span>
          <a-input-number v-model="changeMarkup"></a-input-number>%
        </div>
      </a-modal>
      <a-drawer title="预览" @close="() => { previewTable = false }" :visible="previewTable" width="80%">
        <div style="margin-bottom: 20px;">
          <a-radio-group v-model="applyType" @change="changeViewDataList">
            <a-radio :value="0">未申请</a-radio>
            <a-radio :value="-1">已申请</a-radio>
          </a-radio-group>
        </div>
        <a-table ref="table" :scroll="{ y: tableHeight, x: tableWidth }" :columns="columnsPreview" :dataSource="data2"
          :pagination="false" :loading="loadingPreview" :bordered="true" size="small">

        </a-table>
      </a-drawer>
      <a-drawer title="预览" :width="'100%'" :visible="visiblity" @close="handleCancel">
        <div style="width: 1200px; margin: 0 auto">
          <template>
            <div id="tabPage2">
              <div id="tabPage-zzszyfp">
                <h1 id="fpcc_zp" style="color: #015293; padding: 5px 0px 5px 0px; text-align: center">
                  <strong>{{ this.entity.Type + "(票样)" }}</strong>
                </h1>
                <table border="0" cellpadding="0" cellspacing="0" style="width: 100%">
                  <tbody>
                    <tr height="30">
                      <td class="align_left">
                        发票代码：<span class="content_td_blue" id="fpdm_zp"></span>
                      </td>
                      <td>&nbsp;</td>
                      <td class="align_left">
                        发票号码：<span class="content_td_blue" id="fphm_zp"></span>
                      </td>
                      <td>&nbsp;</td>
                      <td class="align_left">
                        开票日期：<span class="content_td_blue" id="kprq_zp"></span>
                      </td>
                      <td>&nbsp;</td>
                      <td class="align_left">
                        校验码：<span class="content_td_blue" id="jym_zp"></span>
                      </td>
                      <td>&nbsp;</td>
                      <td class="align_left" id="jqxx_zp" style="display: none">
                        机器编号：<span class="content_td_blue" id="jqbh_zp"></span>
                      </td>
                      <td>&nbsp;</td>
                    </tr>
                  </tbody>
                </table>
                <table style="width: 100%" border="1" cellspacing="0" cellpadding="0" class="fppy_table">
                  <tbody>
                    <tr>
                      <td rowspan="4" class="align_center" width="20">
                        <p>购</p>
                        <p>买</p>
                        <p>方</p>
                      </td>
                      <td class="align_left borderNo" width="105">名称：</td>
                      <td nowrap="" class="align_left borderNo bgcolorWhite">
                        <span class="content_td_blue" id="gfmc_zp">{{ this.name }}</span>
                      </td>

                      <td rowspan="4" class="align_center" width="20">
                        <p></p>
                        <p></p>
                        <p></p>
                      </td>
                      <td id="password_zp" rowspan="4" nowrap="" class="align_left" width="350">
                        &nbsp;
                      </td>
                    </tr>
                    <tr>
                      <td class="align_left borderNo">纳税人识别号：</td>
                      <td nowrap="" class="align_left borderNo">
                        <span class="content_td_blue" id="gfsbh_zp">{{
                          entity.zhanghu
                          }}</span>
                      </td>
                    </tr>
                    <tr>
                      <td class="align_left borderNo" valign="top">地址、电话：</td>
                      <td class="align_left borderNo" valign="top">
                        <span class="content_td_blue" id="gfdzdh_zp">{{ entity.phone }}
                        </span>
                      </td>
                    </tr>
                    <tr>
                      <td class="align_left borderNo" valign="top">开户行及账号：</td>
                      <td class="align_left borderNo" valign="top">
                        <span class="content_td_blue" id="gfyhzh_zp">{{
                          entity.kaihu
                          }}</span>
                      </td>
                    </tr>

                    <tr>
                      <td colspan="5">
                        <table cellspacing="0" cellpadding="0" style="width: 100%" class="fppy_table_box">
                          <tbody>
                            <tr id="tab_head_zp">
                              <td class="align_center borderRight" width="30%">
                                货物或应税劳务、服务名称
                              </td>
                              <td class="align_center borderRight" width="10%">
                                规格型号
                              </td>
                              <td class="align_center borderRight" width="5%">单位</td>
                              <td class="align_center borderRight" width="10%">数量</td>
                              <td class="align_center borderRight" width="10%">单价</td>
                              <td class="align_center borderRight" width="15%">金额</td>
                              <td class="align_center borderRight" width="5%">税率</td>
                              <td class="align_center" width="15%">税额</td>
                            </tr>
                            <tr v-for="(item, index) in data2" :key="index">
                              <td class="align_center borderRight" width="30%">
                                {{ item.TM_Name }}
                              </td>
                              <td class="align_center borderRight" width="10%">
                                {{ item.TM_Specs }}
                              </td>
                              <td class="align_center borderRight" width="5%">
                                {{ item.TM_Unit }}
                              </td>
                              <td class="align_center borderRight" width="10%">
                                {{ item.numskk }}
                              </td>
                              <td class="align_center borderRight" width="10%">
                                {{ item.Price?(item.Price ):"" }}
                              </td>
                              <td class="align_center borderRight" width="15%">
                                {{ item.kmoneys }}
                              </td>
                              <td class="align_center borderRight" width="5%">
                                {{ item.TaxRate }}
                              </td>
                              <td class="align_center" width="15%">
                                {{ item.TaxPrice }}
                              </td>
                            </tr>

                            <tr>
                              <td class="align_center borderRight borderTop"></td>
                              <td colspan="4" class="align_left borderTop">
                                <span class="content_td_blue" id="jshjdx_zp"></span>
                              </td>
                              <td style="padding-top: 50px" colspan="3" class="align_left borderTop">
                                <span style="padding: 0 20px">价税合计（小写）</span><span class="content_td_blue"
                                  id="jshjxx_zp">{{
                                  NumberFormats(Number(Amount) - Number(AmountOld))
                                  }}</span>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                      </td>
                    </tr>
                    <tr>
                      <td rowspan="4" class="align_center">
                        <p>销</p>
                        <p>售</p>
                        <p>方</p>
                      </td>
                      <td class="align_left borderNo">名称：</td>
                      <td class="align_left borderNo">
                        <span class="content_td_blue" id="xfmc_zp">{{
                          entity.SellerName
                          }}</span>
                      </td>
                      <td rowspan="4" class="align_center" width="20">
                        <p></p>
                        <p></p>
                      </td>
                      <td rowspan="4" class="align_left content_td_blue" width="350" id="bz_zp" valign="top">
                        &nbsp;
                      </td>
                    </tr>
                    <tr>
                      <td class="align_left borderNo">纳税人识别号：</td>
                      <td class="align_left borderNo">
                        <span class="content_td_blue" id="xfsbh_zp">{{
                          entity.SellerRegcode
                          }}</span>
                      </td>
                    </tr>
                    <tr>
                      <td class="align_left borderNo">地址、电话：</td>
                      <td class="align_left borderNo">
                        <span class="content_td_blue" id="xfdzdh_zp">{{
                          entity.SellerAddress
                          }}</span>
                      </td>
                    </tr>
                    <tr>
                      <td class="align_left borderNo">开户行及账号：</td>
                      <td class="align_left borderNo">
                        <span class="content_td_blue" id="xfyhzh_zp">{{
                          entity.SellerAccbank
                          }}</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </template>
          <div style="display: flex; justify-content: space-between; margin-bottom: 100px"></div>
        </div>
        <div :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }">
          <a-button :style="{ marginRight: '8px' }" @click="handleCancel">上一步</a-button>
          <a-button type="primary" :disabled="submitType" @click="showMergeSame">提交</a-button>
        </div>
      </a-drawer>
    </a-drawer>
    <a-drawer :title="info" width="90%" :visible="visiblees" @close="() => {
      if (this.details) {
        this.visible = false;
      }
      this.visiblees = false;
      this.data2 = [];
      this.allData = [];
    }
      " :body-style="{ paddingBottom: '5%' }">
      <a-form-model :rules="rules" ref="ruleForm" :model="entity" v-bind="layout">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="客户名称:" prop="cusname">
              <a-input v-model="this.cusname" autocomplete="off" :disabled="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="购货方" prop="DicKey">
              <a-select v-if="this.buyPeople.length > 0 && title != '详情'" show-search :disabled="details"
                v-model="entity.DicKey" placeholder="购货方" style="width: 100%" :default-active-first-option="false"
                :show-arrow="false" :filter-option="false" :not-found-content="null" @search="handleSearch"
                @change="handleChange">
                <a-select-option v-for="d in buyPeople" :key="d.cCusName">
                  {{ d.cCusName }}
                </a-select-option>
              </a-select>
              <a-input v-model="entity.DicKey" disabled v-if="title == '详情'"></a-input>
              <!-- <a-select v-if="this.buyPeople.length>0"   placeholder="请选择购货方">
                  <a-select-option v-for="item in buyPeople" :key="item" :value="item.Id" >
                    {{ item. }}
                  </a-select-option>
                </a-select> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="发票类型" prop="Type">
              <a-select show-search :disabled="details" v-model="entity.Type" placeholder="发票类型" style="width: 100%"
                @change="TypeChange">
                <!--<a-select-option value="增值税专用发票">增值税专用发票</a-select-option>
                <a-select-option value="增值税普通发票">增值税普通发票</a-select-option>
                <a-select-option value="增值税电子普通发票">增值税电子普通发票</a-select-option>
                <a-select-option value="增值税电子专用发票">增值税电子专用发票</a-select-option>-->
                <a-select-option value="全电发票(普通发票)">全电发票(普通发票)</a-select-option>
                <a-select-option value="全电发票(专用发票)">全电发票(专用发票)</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="税号" :prop="['增值税普通发票', '增值税电子普通发票', '全电发票(普通发票)'].includes(
      entity.Type
    )
      ? ''
      : 'zhanghu'
      ">
              <a-input :disabled="details" @input="(e) => { }" v-model="entity.zhanghu" placeholder="税号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="开户行及账号:" :prop="['增值税普通发票', '增值税电子普通发票', '全电发票(普通发票)'].includes(
      entity.Type
    )
      ? ''
      : 'kaihu'
      ">
              <a-input :disabled="details" v-model="entity.kaihu" autocomplete="off" placeholder="请使用空格进行分割" />
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="地址、电话" :prop="['增值税普通发票', '增值税电子普通发票', '全电发票(普通发票)'].includes(
      entity.Type
    )
      ? ''
      : 'phone'
      ">
              <a-input :disabled="details" v-model="entity.phone" autocomplete="off" placeholder="请使用空格进行分割" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row> </a-row>
        <div style="display: flex;justify-content: flex-end;">
          <div v-if="!details">
            <a-button style="margin: 0 10px;" type="primary" @click="selectDeleteData">货物名称</a-button>
          </div>
          <div v-if="!details">
            <a-button style="margin: 0 10px;" type="primary" @click="retainDecimal">保留小数</a-button>
          </div>
          <a-button v-if="!details" style="margin: 0 10px;" type="primary" @click="disCountModalShow">折扣</a-button>
          <a-button style="margin: 0 10px;" v-if="!details" type="primary"
            @click="() => { delTaxRateVisibty = true; delTaxRate = '' }">税率删除</a-button>
          <a-button v-if="!details" style="margin-right: 10px;" :disabled="this.selectedRowKeys1.length <= 0"
            type="primary" icon="form" @click="batchChangePrice">批量改价</a-button>
          <a-button v-if="!details" :disabled="this.selectedRowKeys1.length <= 0" type="primary" icon="delete"
            @click="batchDeleteData">批量删除</a-button>
        </div>
        <div style="padding-bottom: 10%; margin-top: 8px">
          <div v-if="Summary">
            <a-tabs default-active-key="1" v-model="setTab" @change="callback">
              <a-tab-pane key="1" tab="明细">
                <a-table ref="table" :scroll="{ y: tableHeight, x: tableWidth }" :columns="columns0" :dataSource="data2"
                  :pagination="false" :rowKey="(row, index) => row.detailcode" :loading="loadingApply" :bordered="true"
                  :row-selection="details ? null : rowSelection" size="small">
                  <template slot="TaxRate" slot-scope="text, record">
                    {{ text ? text.substr(0, text.length - 1) : '' }}
                  </template>
                  <template slot="TM_Name" slot-scope="text, record">
                    <CompanySelect v-if="!details" style="width: 100%" v-model="record.TM_Name"
                      :UnitGroupId="record.ventorycode" :disabled="details" @input="setName($event, record)"
                      @select="project($event, record)"></CompanySelect>
                    <span v-else>{{ record.TM_Name }}</span>
                  </template>
                  <template slot="kmoneys" slot-scope="text, record, index">
                    <span>{{ typeof record.kmoneys == 'string' ? record.kmoneys : (NumberFormats(record.kmoneys)
                      )}}</span>
                  </template>
                  <template slot="Price" slot-scope="text, record">
                    <a-input v-if="!details" :disabled="details" style="width: 100%; text-align: right"
                      v-model="record.Price" @change="(e) => handlePriceChange(e, record)"></a-input>
                    <span v-else>{{ record.Price | NumberFormatss }}</span>
                  </template>
                  <template slot="numskk" slot-scope="text, record, index">
                    <a-input-number v-if="!details" :disabled="details" style="width: 100%; text-align: right"
                      v-model="record.numskk" @change="(e) => handleValChange(e, record, index)"></a-input-number>
                    <span v-else>{{ record.numskk }}</span>
                  </template>
                  <template slot="markup" slot-scope="text, record, index">
                    <template v-if="!details">
                      <a-input-numbera-table :disabled="details" style="width: 80%" v-model="record.markup"
                        @change="(e) => handleValChange(e, record, index, true)"></a-input-numbera-table>
                    </template>
                    <span v-else>{{ record.markup }}</span>
                  </template>
                  <span slot="action" slot-scope="text, record">
                    <template>
                      <a v-if="!details" @click="handleDelete([record])">删除</a>
                    </template>
                  </span>
                </a-table>
              </a-tab-pane>
              <a-tab-pane key="2" tab="汇总">
                <a-table ref="table" :scroll="{ y: tableHeight, x: 800 }" :columns="SummaryColumns"
                  :dataSource="SummaryData" :pagination="false" :rowKey="(row) => row.detailcode"
                  :loading="loadingApply" :bordered="true" :row-selection="details ? null : rowSelection" size="small">
                  <template slot="TaxRate" slot-scope="text, record">
                    {{ text ? text.substr(0, text.length - 1) : '' }}
                  </template>
                  <template slot="TM_Name" slot-scope="text, record">
                    <CompanySelect v-if="!details" style="width: 100%" v-model="record.TM_Name"
                      :UnitGroupId="record.ventorycode" :disabled="details" @input="setName($event, record)"
                      @select="project($event, record)"></CompanySelect>
                    <span v-else>{{ record.TM_Name }}</span>
                  </template>
                  <template slot="InvoicingPrice" slot-scope="text, record">
                    <a-input v-if="!details" :disabled="details" style="width: 100%; text-align: right"
                      v-model="record.InvoicingPrice" @change="(e) => handlePriceChange(e, record)"></a-input>
                    <span v-else>{{ record.InvoicingPrice | NumberFormatss }}</span>
                  </template>
                  <template slot="InvoicingQuantity" slot-scope="text, record, index">
                    <a-input-number v-if="!details" :disabled="details" style="width: 100%"
                      v-model="record.InvoicingQuantity"
                      @change="(e) => handleValChange(e, record, index)"></a-input-number>
                    <span v-else>{{ record.InvoicingQuantity }}</span>
                  </template>
                  <template slot="markup" slot-scope="text, record, index">
                    <template v-if="!details">
                      <a-input-number :disabled="details" style="width: 80%" v-model="record.markup"
                        @change="(e) => handleValChange(e, record, index, true)"></a-input-number>
                    </template>
                    <span v-else>{{ record.markup }}</span>
                  </template>
                  <span slot="action" slot-scope="text, record">
                    <template>
                      <a v-if="!details" @click="handleDelete([record])">删除</a>
                    </template>
                  </span>
                </a-table>
              </a-tab-pane>
              <!-- <a-tab-pane key="3" tab="开票信息">
                <a-table ref="table" :scroll="{ y: tableHeight, x: 800 }" :columns="columnsInvoice"
                  :dataSource="InvoiceData" :pagination="false" :rowKey="(row) => row.detailcode" :loading="loadingApply"
                  :bordered="true" :row-selection="details ? null : rowSelection" size="small">
                  <template slot="TaxRate" slot-scope="text, record">
                    {{ text.substr(0, text.length - 1) }}
                  </template>
                  <template slot="TM_Name" slot-scope="text, record">
                    <CompanySelect v-if="!details" style="width: 100%" v-model="record.TM_Name"
                      :UnitGroupId="record.ventorycode" :disabled="details" @input="setName($event, record)"
                      @select="project($event, record)"></CompanySelect>
                    <span v-else>{{ record.TM_Name }}</span>
                  </template>
                  <template slot="InvoicingPrice" slot-scope="text, record">
                    <a-input v-if="!details" :disabled="details" style="width: 100%; text-align: right"
                      v-model="record.InvoicingPrice" @change="(e) => handlePriceChange(e, record)"></a-input>
                    <span v-else>{{ record.InvoicingPrice | NumberFormatss }}</span>
                  </template>
                  <template slot="InvoicingQuantity" slot-scope="text, record, index">
                    <a-input-number v-if="!details" :disabled="details" style="width: 100%"
                      v-model="record.InvoicingQuantity"
                      @change="(e) => handleValChange(e, record, index)"></a-input-number>
                    <span v-else>{{ record.InvoicingQuantity }}</span>
                  </template>
                  <template slot="markup" slot-scope="text, record, index">
                    <template v-if="!details">
                      <a-input-number :disabled="details" style="width: 80%" v-model="record.markup"
                        @change="(e) => handleValChange(e, record, index, true)"></a-input-number>
                    </template>
                    <span v-else>{{ record.markup }}</span>
                  </template>
                  <span slot="action" slot-scope="text, record">
                    <template>
                      <a v-if="!details" @click="handleDelete([record])">删除</a>
                    </template>
                  </span>
                </a-table>
              </a-tab-pane>
              <a-tab-pane key="4" tab="出库信息">
                <a-table ref="table" :scroll="{ y: tableHeight, x: 800 }" :columns="columnsOutbound"
                  :dataSource="OutboundData" :pagination="false" :rowKey="(row) => row.detailcode" :loading="loadingApply"
                  :bordered="true" :row-selection="details ? null : rowSelection" size="small">
                  <template slot="TaxRate" slot-scope="text, record">
                    {{ text.substr(0, text.length - 1) }}
                  </template>
                  <template slot="TM_Name" slot-scope="text, record">
                    <CompanySelect v-if="!details" style="width: 100%" v-model="record.TM_Name"
                      :UnitGroupId="record.ventorycode" :disabled="details" @input="setName($event, record)"
                      @select="project($event, record)"></CompanySelect>
                    <span v-else>{{ record.TM_Name }}</span>
                  </template>
                  <template slot="InvoicingPrice" slot-scope="text, record">
                    <a-input v-if="!details" :disabled="details" style="width: 100%; text-align: right"
                      v-model="record.InvoicingPrice" @change="(e) => handlePriceChange(e, record)"></a-input>
                    <span v-else>{{ record.InvoicingPrice | NumberFormatss }}</span>
                  </template>
                  <template slot="InvoicingQuantity" slot-scope="text, record, index">
                    <a-input-number v-if="!details" :disabled="details" style="width: 100%"
                      v-model="record.InvoicingQuantity"
                      @change="(e) => handleValChange(e, record, index)"></a-input-number>
                    <span v-else>{{ record.InvoicingQuantity }}</span>
                  </template>
                  <template slot="markup" slot-scope="text, record, index">
                    <template v-if="!details">
                      <a-input-number :disabled="details" style="width: 80%" v-model="record.markup"
                        @change="(e) => handleValChange(e, record, index, true)"></a-input-number>
                    </template>
                    <span v-else>{{ record.markup }}</span>
                  </template>
                  <span slot="action" slot-scope="text, record">
                    <template>
                      <a v-if="!details" @click="handleDelete([record])">删除</a>
                    </template>
                  </span>
                </a-table>
              </a-tab-pane>
              <a-tab-pane key="5" tab="订单">
                <a-table ref="table" :scroll="{ y: tableHeight, x: 800 }" :columns="columnsOrder" :dataSource="OrderData"
                  :pagination="false" :rowKey="(row) => row.detailcode" :loading="loadingApply" :bordered="true"
                  :row-selection="details ? null : rowSelection" size="small">
                  <template slot="TaxRate" slot-scope="text, record">
                    {{ text.substr(0, text.length - 1) }}
                  </template>
                  <template slot="TM_Name" slot-scope="text, record">
                    <CompanySelect v-if="!details" style="width: 100%" v-model="record.TM_Name"
                      :UnitGroupId="record.ventorycode" :disabled="details" @input="setName($event, record)"
                      @select="project($event, record)"></CompanySelect>
                    <span v-else>{{ record.TM_Name }}</span>
                  </template>
                  <template slot="InvoicingPrice" slot-scope="text, record">
                    <a-input v-if="!details" :disabled="details" style="width: 100%; text-align: right"
                      v-model="record.InvoicingPrice" @change="(e) => handlePriceChange(e, record)"></a-input>
                    <span v-else>{{ record.InvoicingPrice | NumberFormatss }}</span>
                  </template>
                  <template slot="InvoicingQuantity" slot-scope="text, record, index">
                    <a-input-number v-if="!details" :disabled="details" style="width: 100%"
                      v-model="record.InvoicingQuantity"
                      @change="(e) => handleValChange(e, record, index)"></a-input-number>
                    <span v-else>{{ record.InvoicingQuantity }}</span>
                  </template>
                  <template slot="markup" slot-scope="text, record, index">
                    <template v-if="!details">
                      <a-input-number :disabled="details" style="width: 80%" v-model="record.markup"
                        @change="(e) => handleValChange(e, record, index, true)"></a-input-number>
                    </template>
                    <span v-else>{{ record.markup }}</span>
                  </template>
                  <span slot="action" slot-scope="text, record">
                    <template>
                      <a v-if="!details" @click="handleDelete([record])">删除</a>
                    </template>
                  </span>
                </a-table>
              </a-tab-pane>
              <a-tab-pane key="6" tab="销货信息">
                <a-table ref="table" :scroll="{ y: tableHeight, x: 800 }" :columns="columnsSales" :dataSource="SalesData"
                  :pagination="false" :rowKey="(row) => row.detailcode" :loading="loadingApply" :bordered="true"
                  :row-selection="details ? null : rowSelection" size="small">
                  <template slot="TaxRate" slot-scope="text, record">
                    {{ text.substr(0, text.length - 1) }}
                  </template>
                  <template slot="TM_Name" slot-scope="text, record">
                    <CompanySelect v-if="!details" style="width: 100%" v-model="record.TM_Name"
                      :UnitGroupId="record.ventorycode" :disabled="details" @input="setName($event, record)"
                      @select="project($event, record)"></CompanySelect>
                    <span v-else>{{ record.TM_Name }}</span>
                  </template>
                  <template slot="InvoicingPrice" slot-scope="text, record">
                    <a-input v-if="!details" :disabled="details" style="width: 100%; text-align: right"
                      v-model="record.InvoicingPrice" @change="(e) => handlePriceChange(e, record)"></a-input>
                    <span v-else>{{ record.InvoicingPrice | NumberFormatss }}</span>
                  </template>
                  <template slot="InvoicingQuantity" slot-scope="text, record, index">
                    <a-input-number v-if="!details" :disabled="details" style="width: 100%"
                      v-model="record.InvoicingQuantity"
                      @change="(e) => handleValChange(e, record, index)"></a-input-number>
                    <span v-else>{{ record.InvoicingQuantity }}</span>
                  </template>
                  <template slot="markup" slot-scope="text, record, index">
                    <template v-if="!details">
                      <a-input-number :disabled="details" style="width: 80%" v-model="record.markup"
                        @change="(e) => handleValChange(e, record, index, true)"></a-input-number>
                    </template>
                    <span v-else>{{ record.markup }}</span>
                  </template>
                  <span slot="action" slot-scope="text, record">
                    <template>
                      <a v-if="!details" @click="handleDelete([record])">删除</a>
                    </template>
                  </span>
                </a-table>
              </a-tab-pane> -->
            </a-tabs>
          </div>
          <a-table v-else ref="table" :scroll="{ y: tableHeight, x: tableWidth }" :columns="columns0"
            :dataSource="data2" :pagination="false" :rowKey="(row) => row.detailcode" :loading="loadingApply"
            :bordered="true" :row-selection="details ? null : rowSelection" size="small">
            <template slot="TaxRate" slot-scope="text, record">
              {{ text ? text.substr(0, text.length - 1) : '' }}
            </template>
            <template slot="TM_Name" slot-scope="text, record">
              <CompanySelect v-if="!details && !record.disCountType" style="width: 100%" v-model="record.TM_Name"
                :UnitGroupId="record.ventorycode" :disabled="details" @input="setName($event, record)"
                @select="project($event, record)"></CompanySelect>
              <span v-else>{{ record.TM_Name }}</span>
            </template>
            <template slot="Price" slot-scope="text, record">
              <a-input v-if="!details && !record.disCountType" :disabled="details"
                style="width: 100%; text-align: right" v-model="record.Price"
                @change="(e) => handlePriceChange(e, record)"></a-input>
              <span v-else>{{ record.Price?(record.Price | NumberFormatss) :''}}</span>
            </template>
            <template slot="numskk" slot-scope="text, record, index">
              <a-input v-if="!details && !record.disCountType" :disabled="details"
                style="width: 100%; text-align: right" v-model="record.numskk" @input="setMon(record)"
                @change="calcAmount(true,record)"></a-input>
              <span v-else>{{ record.numskk }}</span>
            </template>
            <template slot="markup" slot-scope="text, record, index">
              <template v-if="!details && !record.disCountType">
                <a-input-number :disabled="details" style="width: 80%" v-model="record.markup"
                  @change="calcAmount"></a-input-number>
              </template>
              <span v-else>{{ record.markup }}</span>
            </template>
            <template slot="kmoneys" slot-scope="text, record, index">
              <span>{{ typeof record.kmoneys == 'string' ? record.kmoneys : (NumberFormats(record.kmoneys)) }}</span>
            </template>
            <span slot="action" slot-scope="text, record">
              <template>
                <a v-if="!details" @click="handleDelete([record])">删除</a>
              </template>
            </span>
          </a-table>
        </div>
        <p></p>
        <a-row style="
            position: fixed;
            bottom: 5%;
            z-index: 999999;
            width: 88%;
            background-color: #fff;
          ">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <a-switch v-if="details" style="margin-left: 20px;" disabled v-model:checked="IsMerge"
              checked-children="合并相同项" un-checked-children="不合并相同项" />
            <p style="text-align: right; margin-right: 20px">
              <span>数量合计<span></span> {{ Count || 0.00 }}</span>
              <span style="margin-left: 30px;">原价合计<span></span> {{ Amount | NumberFormats }}</span>
              <span style="margin-left: 30px;">价税合计<span></span> {{ NumberFormats(Number(Amount) - Number(AmountOld)) ||
                0 }}</span>
              <span style="margin-left: 30px;color: red;">折扣额合计 <span v-if="AmountOld != '0.00'">-</span>{{ AmountOld
                | NumberFormats }}</span>
            </p>
          </div>
          <a-col :span="8">
            <a-form-model-item label="收票人:" prop="shoupiaoren">
              <a-input :disabled="details" v-model="entity.shoupiaoren" autocomplete="off" placeholder="收票人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="手机号:" prop="Phone">
              <a-input :disabled="details" v-model="entity.Phone" autocomplete="off" placeholder="收票人手机号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="收票地址:" prop="shoupiaodizhi">
              <a-textarea :disabled="details" v-model="entity.shoupiaodizhi" autocomplete="off" placeholder="收票地址" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="邮箱地址:" prop="cCusEmail">
              <a-input :disabled="details" v-model="entity.cCusEmail" autocomplete="off" placeholder="邮箱地址" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="说明:" prop="Remarks">
              <a-input :disabled="details" v-model="entity.Remarks" autocomplete="off" placeholder="说明" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" prop="Remark">
              <a-textarea :disabled="details" v-model="entity.Remark" autocomplete="off" placeholder="备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div :style="{
      position: 'absolute',
      right: 0,
      bottom: 0,
      width: '100%',
      borderTop: '1px solid #e9e9e9',
      padding: '10px 16px',
      background: '#fff',
      textAlign: 'right',
      zIndex: 9999999999,
    }">
        <a-button v-if="!details" :style="{ marginRight: '8px' }" @click="shouorderforgoods">上一步</a-button>
        <a-button v-if="!details" type="primary" @click="SummarySubmission">下一步</a-button>
        <a-button v-if="details" type="primary" @click="closeDetails">取消</a-button>
      </div>
    </a-drawer>
    <a-modal :width="400" style="text-align: center;" title="提交" :visible="mergeSameShow" @ok="handleOk"
      @cancel="() => { IsMerge = false, mergeSameShow = false }">
      <a-switch class="my-switch" style="margin: 30px 0;" v-model:checked="IsMerge" checked-children="合并相同项"
        un-checked-children="不合并相同项" />
    </a-modal>
    <a-modal :width="1200" style="text-align: center;" title="货物名称" :visible="selectDeleteVisible" @ok="handlePushData"
      @cancel="() => { selectDeleteVisible = false }">
      <a-table ref="table" :scroll="{ y: tableHeight, x: tableWidth }" :columns="columnsDel" :dataSource="delData"
        :pagination="false" :rowKey="(row, index) => row.detailcode" :loading="loadingPreview" :bordered="true"
        :row-selection="rowSelectionDel" size="small">
        <template slot="TaxRate" slot-scope="text, record">
          {{ text ? text.substr(0, text.length - 1) : '' }}
        </template>
        <template slot="TM_Name" slot-scope="text, record">
          <span>{{ record.TM_Name }}</span>
        </template>
        <template slot="Price" slot-scope="text, record">
          <span>{{ record.Price | NumberFormatss }}</span>
        </template>
        <template slot="numskk" slot-scope="text, record, index">
          <span>{{ record.numskk }}</span>
        </template>
        <template slot="markup" slot-scope="text, record, index">
          <span>{{ record.markup }}</span>
        </template>
      </a-table>
    </a-modal>
    <a-modal title="请输入折扣金额" @ok="disCountOk" width="10%" :visible="disCountModalVisibly"
      @cancel="() => { disCount = '', disCountModalVisibly = false }">
      <div style="display:flex;justify-content: center;align-items: center">
        <a-input placeholder="折扣金额" v-model="disCount"></a-input>
      </div>
    </a-modal>
    <a-modal title="保留小数位数" @ok="handleRetainDecimal" width="10%" :visible="retainDecimalVisible"
      @cancel="() => { retainDecimalVisible = false }">
      <div style="display:flex;justify-content: center;align-items: center">
        <a-input-number style="width: 200px" :max="8" v-model="retainDecimalCount"></a-input-number>
      </div>
    </a-modal>
    <a-modal title="税率删除" @ok="delTaxRateFilter" width="10%" :visible="delTaxRateVisibty"
      @cancel="() => { delTaxRateVisibty = false } ">
      <a-input style="width: 100px;" v-model=" delTaxRate " placeholder="税率"></a-input>
    </a-modal>
  </div>
</template>
<script>
import SearchCusinfo from './SearchCusinfo'
import moment from 'moment'
import CompanySelect from '@/components/PB/CompanySelect'
import { invoicemixin } from '@/utils/invoiceApplicationmixin.js'

const columnsRead = [
  {
    title: '货物或应税劳务、服务名称',
    dataIndex: 'TM_Name',
    scopedSlots: { customRender: 'TM_Name' }
  },
  {
    title: '规格型号',
    dataIndex: 'TM_Specs'
  },
  {
    title: '单位',
    dataIndex: 'TM_Unit'
  },
  {
    title: '数 量',
    dataIndex: 'numskk'
  },
  {
    title: '单 价',
    dataIndex: 'Price'
  },
  {
    title: '金 额',
    dataIndex: 'kmoneys'
  },
  {
    title: '税率%',
    dataIndex: 'TaxRate'
  },
  {
    title: '税 额',
    dataIndex: 'TaxPrice'
  }
]
const columnsPreview = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '出库单号', dataIndex: 'code', width: '150px', align: 'right' },
  { title: '货物编码', dataIndex: 'ventorycode', width: '100px', align: 'right' },
  { title: '货物名称', dataIndex: 'ventoryname', width: '150px', align: 'right' },
  { title: '规格型号', dataIndex: 'specification', width: '150px', align: 'right' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px', align: 'right' },
  { title: '出库数量', dataIndex: 'quantity', width: '100px', align: 'right' },
  {
    title: '出库金额',
    dataIndex: 'origTaxSaleAmount',
    width: '100px',
    align: 'right',
    hidden: true
  },
  { title: '已开数量', dataIndex: 'Openedquantity', width: '100px', align: 'right' },
  { title: '签收数量', dataIndex: 'ReceivedQuantity', width: '100px', align: 'right' },
  {
    title: '开票使用名称',
    dataIndex: 'TM_Name',
    width: '300px',
    align: 'center',
    scopedSlots: { customRender: 'TM_Name' }
  },
  { title: '标准售价', dataIndex: 'origTaxSalePrice', width: '150px', align: 'right' },
  {
    title: '加成率%',
    dataIndex: 'markup',
    width: '100px',
    align: 'right',
    scopedSlots: { customRender: 'markup' }
  },
  {
    title: '开票价格',
    dataIndex: 'Price',
    width: '200px',
    align: 'right',
    scopedSlots: { customRender: 'Price' }
  },
  {
    title: '数量',
    dataIndex: 'numskk',
    width: '100px',
    align: 'right',
    scopedSlots: { customRender: 'numskk' }
  },
  { title: '含税金额', dataIndex: 'kmoneys', width: '150px', align: 'right' },
  {
    title: '税率%',
    dataIndex: 'TaxRate',
    width: '100px',
    align: 'right',
    scopedSlots: { customRender: 'TaxRate' }
  },
  { title: '税额', dataIndex: 'TaxPrice', width: '150px', align: 'right' },
]
const columnsDel = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '出库单号', dataIndex: 'code', width: '150px', align: 'right' },
  { title: '货物编码', dataIndex: 'ventorycode', width: '100px', align: 'right' },
  { title: '货物名称', dataIndex: 'ventoryname', width: '150px', align: 'right' },
  { title: '规格型号', dataIndex: 'specification', width: '150px', align: 'right' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px', align: 'right' },
  // { title: '出库数量', dataIndex: 'quantity', width: '100px', align: 'right' },
  // {
  //   title: '出库金额',
  //   dataIndex: 'origTaxSaleAmount',
  //   width: '100px',
  //   align: 'right',
  //   hidden: true
  // },
  // { title: '已开数量', dataIndex: 'Openedquantity', width: '100px', align: 'right' },
  // { title: '签收数量', dataIndex: 'ReceivedQuantity', width: '100px', align: 'right' },
  {
    title: '开票使用名称',
    dataIndex: 'TM_Name',
    width: '300px',
    align: 'center',
    scopedSlots: { customRender: 'TM_Name' }
  },
  { title: '标准售价', dataIndex: 'origTaxSalePrice', width: '150px', align: 'right' },
  {
    title: '加成率%',
    dataIndex: 'markup',
    width: '100px',
    align: 'right',
    scopedSlots: { customRender: 'markup' }
  },
  {
    title: '开票价格',
    dataIndex: 'Price',
    width: '200px',
    align: 'right',
    scopedSlots: { customRender: 'Price' }
  },
  {
    title: '数量',
    dataIndex: 'numskk',
    width: '100px',
    align: 'right',
    scopedSlots: { customRender: 'numskk' }
  },
  { title: '含税金额', dataIndex: 'kmoneys', width: '150px', align: 'right' },
  {
    title: '税率%',
    dataIndex: 'TaxRate',
    width: '100px',
    align: 'right',
    scopedSlots: { customRender: 'TaxRate' }
  },
  { title: '税额', dataIndex: 'TaxPrice', width: '150px', align: 'right' },
]
const columns = [
  { title: '发货日期', dataIndex: 'MadeDate', width: '100px', scopedSlots: { customRender: 'MadeDate' } },
  { title: '发票单号', dataIndex: 'BillId', width: '140px' },
  { title: '客户名称', dataIndex: 'Customer' },
  {
    title: '总数量',
    dataIndex: 'TotalQuantity',
    align: 'right',
    customRender: (val) => {
      if (!val) {
        return 0
      } else {
        return val
      }
    },
    width: '100px'
  },
  {
    title: '已申请数量',
    dataIndex: 'ApplyTotalQuantity',
    align: 'right',
    customRender: (val) => {
      if (!val) {
        return 0
      } else {
        return val
      }
    },
    width: '100px'
  },
  {
    title: '总金额',
    dataIndex: 'TotalMoney',
    align: 'right',
    width: '110px',
    customRender: (value) => {
      const originalValue = parseFloat(Number(value).toFixed(2))
      // 使用toLocaleString方法将数字格式化为千分位表示
      let res = originalValue.toLocaleString()
      const match = res.match(/\.(\d+)/)
      if (match && match[1].length === 1) {
        // 如果找到匹配小数点后面的数字的长度加0   /'22.4'+0
        return (res += '0')
      } else if ((match && match[1].length == 0) || !match) {
        return (res += '.00')
      } else {
        // 如果没有匹配小数部分长度，返回原数字。
        return res
      }
    }

    // 获取元素的文本内容
  },
  { title: '摘要', dataIndex: 'SendMessage' },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '50px' }
  // { title: '联系人', dataIndex: 'Contact', width: '10%' },
  // { title: '联系电话', dataIndex: 'ContactPhone', width: '15%' }
].filter((v) => !v.hidden) // 增加filter过滤
// 新建
const columns2 = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '出库单号', dataIndex: 'code', width: '150px', align: 'right' },
  { title: '货物编码', dataIndex: 'ventorycode', width: '100px', align: 'right' },
  { title: '货物名称', dataIndex: 'ventoryname', width: '150px', align: 'right' },
  { title: '规格型号', dataIndex: 'specification', width: '150px', align: 'right' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px', align: 'right' },
  { title: '出库数量', dataIndex: 'quantity', width: '100px', align: 'right' },
  {
    title: '出库金额',
    dataIndex: 'origTaxSaleAmount',
    width: '100px',
    align: 'right',
    hidden: true
  },
  { title: '已开数量', dataIndex: 'Openedquantity', width: '100px', align: 'right' },
  { title: '签收数量', dataIndex: 'ReceivedQuantity', width: '100px', align: 'right' },
  {
    title: '开票使用名称',
    dataIndex: 'TM_Name',
    width: '300px',
    align: 'center',
    scopedSlots: { customRender: 'TM_Name' }
  },
  { title: '标准售价', dataIndex: 'origTaxSalePrice', width: '150px', align: 'right' },
  {
    title: '加成率%',
    dataIndex: 'markup',
    width: '100px',
    align: 'right',
    scopedSlots: { customRender: 'markup' }
  },
  {
    title: '开票价格',
    dataIndex: 'Price',
    width: '200px',
    align: 'right',
    scopedSlots: { customRender: 'Price' }
  },
  {
    title: '数量',
    dataIndex: 'numskk',
    width: '100px',
    align: 'right',
    scopedSlots: { customRender: 'numskk' }
  },
  { title: '含税金额', dataIndex: 'kmoneys', width: '150px', align: 'right', scopedSlots: { customRender: 'kmoneys' }, },
  {
    title: '税率%',
    dataIndex: 'TaxRate',
    width: '100px',
    align: 'right',
    scopedSlots: { customRender: 'TaxRate' }
  },
  { title: '税额', dataIndex: 'TaxPrice', width: '150px', align: 'right' },
  // {
  //   title: '操作',
  //   dataIndex: 'action',
  //   scopedSlots: { customRender: 'action' },
  //   width: '60px',
  //   fixed: 'right'
  // }
].filter((v) => !v.hidden) // 增加filter过滤
// 详情
const columns3 = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '出库单号', dataIndex: 'code', hidden: true },
  { title: '货物编码', dataIndex: 'ventorycode', width: '100px', align: 'right' },
  { title: '货物名称', dataIndex: 'ventoryname', width: '150px', align: 'right' },
  { title: '规格型号', dataIndex: 'specification', width: '150px', align: 'right' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px', align: 'right' },
  { title: '出库金额', dataIndex: 'origTaxSaleAmount', align: 'right', hidden: true },
  {
    title: '开票使用名称',
    dataIndex: 'TM_Name',
    width: '300px',
    scopedSlots: { customRender: 'TM_Name' },
    align: 'center'
  },
  { title: '标准售价', dataIndex: 'origTaxSalePrice', align: 'right', width: '150px' },
  {
    title: '加成率%',
    dataIndex: 'markup',
    align: 'right',
    scopedSlots: { customRender: 'markup' },
    width: '80px'
  },
  {
    title: '开票价格',
    dataIndex: 'Price',
    align: 'right',
    scopedSlots: { customRender: 'Price' },
    width: '160px'
  },
  {
    title: '数量',
    dataIndex: 'numskk',
    align: 'right',
    scopedSlots: { customRender: 'numskk' },
    width: '80px'
  },
  { title: '含税金额', dataIndex: 'kmoneys', align: 'right', width: '150px' },
  {
    title: '税率%',
    dataIndex: 'TaxRate',
    align: 'right',
    width: '60px',
    scopedSlots: { customRender: 'TaxRate' }
  },
  { title: '税额', dataIndex: 'TaxPrice', align: 'right', width: '150px' }
].filter((v) => !v.hidden) // 增加filter过滤
//开票信息
const columnsInvoice = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '出库单号', dataIndex: 'code', hidden: true },
  { title: '货物编码', dataIndex: 'ventorycode', width: '100px', align: 'right' },
  { title: '货物名称', dataIndex: 'ventoryname', width: '150px', align: 'right' },
  { title: '规格型号', dataIndex: 'specification', width: '150px', align: 'right' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px', align: 'right' },
  { title: '出库金额', dataIndex: 'origTaxSaleAmount', align: 'right', hidden: true },
  {
    title: '开票使用名称',
    dataIndex: 'TM_Name',
    width: '300px',
    scopedSlots: { customRender: 'TM_Name' },
    align: 'center'
  },
  { title: '标准售价', dataIndex: 'origTaxSalePrice', align: 'right', width: '150px' },
  {
    title: '加成率%',
    dataIndex: 'markup',
    align: 'right',
    scopedSlots: { customRender: 'markup' },
    width: '80px'
  },
  {
    title: '开票价格',
    dataIndex: 'Price',
    align: 'right',
    scopedSlots: { customRender: 'Price' },
    width: '160px'
  },
  {
    title: '数量',
    dataIndex: 'numskk',
    align: 'right',
    scopedSlots: { customRender: 'numskk' },
    width: '80px'
  },
  { title: '含税金额', dataIndex: 'kmoneys', align: 'right', width: '150px' },
  {
    title: '税率%',
    dataIndex: 'TaxRate',
    align: 'right',
    width: '60px',
    scopedSlots: { customRender: 'TaxRate' }
  },
  { title: '税额', dataIndex: 'TaxPrice', align: 'right', width: '150px' }
].filter((v) => !v.hidden) // 增加filter过滤
// 出库信息
const columnsOutbound = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '出库单号', dataIndex: 'code', hidden: true },
  { title: '货物编码', dataIndex: 'ventorycode', width: '100px', align: 'right' },
  { title: '货物名称', dataIndex: 'ventoryname', width: '150px', align: 'right' },
  { title: '规格型号', dataIndex: 'specification', width: '150px', align: 'right' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px', align: 'right' },
  { title: '出库金额', dataIndex: 'origTaxSaleAmount', align: 'right', hidden: true },
  {
    title: '开票使用名称',
    dataIndex: 'TM_Name',
    width: '300px',
    scopedSlots: { customRender: 'TM_Name' },
    align: 'center'
  },
  { title: '标准售价', dataIndex: 'origTaxSalePrice', align: 'right', width: '150px' },
  {
    title: '加成率%',
    dataIndex: 'markup',
    align: 'right',
    scopedSlots: { customRender: 'markup' },
    width: '80px'
  },
  {
    title: '开票价格',
    dataIndex: 'Price',
    align: 'right',
    scopedSlots: { customRender: 'Price' },
    width: '160px'
  },
  {
    title: '数量',
    dataIndex: 'numskk',
    align: 'right',
    scopedSlots: { customRender: 'numskk' },
    width: '80px'
  },
  { title: '含税金额', dataIndex: 'kmoneys', align: 'right', width: '150px' },
  {
    title: '税率%',
    dataIndex: 'TaxRate',
    align: 'right',
    width: '60px',
    scopedSlots: { customRender: 'TaxRate' }
  },
  { title: '税额', dataIndex: 'TaxPrice', align: 'right', width: '150px' }
].filter((v) => !v.hidden) // 增加filter过滤
//订单
const columnsOrder = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '出库单号', dataIndex: 'code', hidden: true },
  { title: '货物编码', dataIndex: 'ventorycode', width: '100px', align: 'right' },
  { title: '货物名称', dataIndex: 'ventoryname', width: '150px', align: 'right' },
  { title: '规格型号', dataIndex: 'specification', width: '150px', align: 'right' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px', align: 'right' },
  { title: '出库金额', dataIndex: 'origTaxSaleAmount', align: 'right', hidden: true },
  {
    title: '开票使用名称',
    dataIndex: 'TM_Name',
    width: '300px',
    scopedSlots: { customRender: 'TM_Name' },
    align: 'center'
  },
  { title: '标准售价', dataIndex: 'origTaxSalePrice', align: 'right', width: '150px' },
  {
    title: '加成率%',
    dataIndex: 'markup',
    align: 'right',
    scopedSlots: { customRender: 'markup' },
    width: '80px'
  },
  {
    title: '开票价格',
    dataIndex: 'Price',
    align: 'right',
    scopedSlots: { customRender: 'Price' },
    width: '160px'
  },
  {
    title: '数量',
    dataIndex: 'numskk',
    align: 'right',
    scopedSlots: { customRender: 'numskk' },
    width: '80px'
  },
  { title: '含税金额', dataIndex: 'kmoneys', align: 'right', width: '150px' },
  {
    title: '税率%',
    dataIndex: 'TaxRate',
    align: 'right',
    width: '60px',
    scopedSlots: { customRender: 'TaxRate' }
  },
  { title: '税额', dataIndex: 'TaxPrice', align: 'right', width: '150px' }
].filter((v) => !v.hidden) // 增加filter过滤
// 销货信息
const columnsSales = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '出库单号', dataIndex: 'code', hidden: true },
  { title: '货物编码', dataIndex: 'ventorycode', width: '100px', align: 'right' },
  { title: '货物名称', dataIndex: 'ventoryname', width: '150px', align: 'right' },
  { title: '规格型号', dataIndex: 'specification', width: '150px', align: 'right' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px', align: 'right' },
  { title: '出库金额', dataIndex: 'origTaxSaleAmount', align: 'right', hidden: true },
  {
    title: '开票使用名称',
    dataIndex: 'TM_Name',
    width: '300px',
    scopedSlots: { customRender: 'TM_Name' },
    align: 'center'
  },
  { title: '标准售价', dataIndex: 'origTaxSalePrice', align: 'right', width: '150px' },
  {
    title: '加成率%',
    dataIndex: 'markup',
    align: 'right',
    scopedSlots: { customRender: 'markup' },
    width: '80px'
  },
  {
    title: '开票价格',
    dataIndex: 'Price',
    align: 'right',
    scopedSlots: { customRender: 'Price' },
    width: '160px'
  },
  {
    title: '数量',
    dataIndex: 'numskk',
    align: 'right',
    scopedSlots: { customRender: 'numskk' },
    width: '80px'
  },
  { title: '含税金额', dataIndex: 'kmoneys', align: 'right', width: '150px' },
  {
    title: '税率%',
    dataIndex: 'TaxRate',
    align: 'right',
    width: '60px',
    scopedSlots: { customRender: 'TaxRate' }
  },
  { title: '税额', dataIndex: 'TaxPrice', align: 'right', width: '150px' }
].filter((v) => !v.hidden) // 增加filter过滤

// 汇总
const SummaryColumns = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  // { title: '出库单号', dataIndex: 'code', hidden: true },
  { title: '货物编码', dataIndex: 'code', width: '200px', align: 'right' },
  { title: '货物名称', dataIndex: 'name', width: '150px', align: 'right' },
  { title: '规格型号', dataIndex: 'specification', width: '150px', align: 'right' },
  // { title: '单位', dataIndex: 'compositionQuantity', width: '100px' },
  // { title: '出库金额', dataIndex: 'origTaxSaleAmount', align: 'right', hidden: true, },
  // { title: '开票使用名称', dataIndex: 'TM_Name', scopedSlots: { customRender: 'TM_Name' }, align: 'center', width: '120px' },
  // { title: '基本售价', dataIndex: 'InvoicingPrice', align: 'right', width: '150px' },
  // { title: '加成率%', dataIndex: 'markup', align: 'right', scopedSlots: { customRender: 'markup' }, width: '80px' },
  {
    title: '开票价格',
    dataIndex: 'InvoicingPrice',
    align: 'right',
    scopedSlots: { customRender: 'InvoicingPrice' },
    width: '160px'
  },
  {
    title: '数量',
    dataIndex: 'InvoicingQuantity',
    align: 'right',
    scopedSlots: { customRender: 'InvoicingQuantity' },
    width: '80px'
  },
  { title: '含税金额', dataIndex: 'InvoicingAmount', align: 'right', width: '160px' },
  // { title: '税率%', dataIndex: 'TaxRate', align: 'right', width: '60px' },
  { title: '税额', dataIndex: 'TaxAmount', align: 'right', width: '160px' }
].filter((v) => !v.hidden) // 增加filter过滤
export default {
  components: {
    SearchCusinfo,
    CompanySelect
  },
  props: ['back', 'parentObj'],
  data() {
    return {
      columnsRead,
      columnsPreview,
      loadingPreview: false,
      spinloading: false,
      parentId: '',
      timeDisabled: true,
      delTaxRate: '',
      Amountyuan:0,
      delVentoryname: '',
      delData: [],
      columnsDel,
      disCount: "",
      disCountModalVisibly: false,
      options: [
        {
          value: 0,
          label: '张三',
          address: '地址0',
          phone: '0'
        },
        {
          value: 1,
          label: '李四',
          address: '地址1',
          phone: '1'
        },
        {
          value: 2,
          label: '王五',
          address: '地址2',
          phone: '2'
        }
      ],
      details: false,
      Amount: 0,
      data: [],
      start: 0,
      SummaryData: [],
      InvoiceData: [],
      OutboundData: [],
      OrderData: [],
      delTaxRateVisibty:false,
      SalesData: [],
      data2: [],
      allData: [],
      Preview: [],
      selectedRowKeys: [],
      selectedRows: [],
      tableWidth: 0,
      name: '',
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      columns3,
      columnsInvoice,
      columnsOutbound,
      columnsOrder,
      columnsSales,
      info: '',
      PriceCount: 0,
      buyPeopleRead: [],
      visiblity: false,
      setTab: '1',
      tableHeight2:0,
      SummaryColumns,
      changeVisible: false,
      loadingApply: false,
      changeMarkup: '', // 批量修改加成率
      Summary: false,
      mergeSameShow: false,
      previewTable: false,
      pagination: {
        current: 1,
        pageSize: 20,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100','500'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      columns0: [],
      AmountOld:0,
      pagination2: {
        current: 1,
        pageSize: 20,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      sorter: { field: 'code', order: 'desc' },
      columns,
      columns2,
      OutboundOrder: '',
      submitType: false,
      cusid: '',
      time: [],
      buyPeople: [],
      IsMerge: false,
      cusname: '',
      queryParam: {
        condition: 'code'
      },
      visible: false,
      visiblees: false,
      data2Old:[],
      loading: false,
      retainDecimalVisible:false,
      retainDecimalCount:2,
      rules: {
        DicKey: [{ required: true, message: '请填写', trigger: 'change' }],
        Type: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
        zhanghu: [
          { required: true, message: '请填写9至20位税号', trigger: 'blur' },
          { min: 9, max: 20, message: '请填写9至20位税号', trigger: 'blur' }
        ],
        kaihu: [{ required: true, message: '请填写', trigger: 'blur' }],
        phone: [{ required: true, message: '请填写', trigger: 'blur' }]
        // Remarks: [{ required: true, message: '请填写', trigger: 'change' }],
        // shoupiaoren: [{ required: true, message: '请填写', trigger: 'change' }],
        // Phone: [{ required: true, message: '请填写', trigger: 'change' }],
        // shoupiaodizhi: [{ required: true, message: '请填写', trigger: 'change' }],
        // beizhu: [{ required: true, message: '请填写', trigger: 'change' }],
      },
      title: '',
      entity: { DicKey: '' },
      flag: true,
      timer: null,
      applyType:0,
      tableHeight: 0,
      precision: 1e10,
      Count:"0.00",
      userInfo: {},
      newArr: [],
      selectedRowKeys1: [],
      cancel: false,
      selectDeleteVisible: false,
      selectedRowKeysDel: [],
    }
  },
  computed: {
    // Count() {
    //   let count = 0;
    //   this.data2.forEach(item => {
    //     count += Number(item.numskk)
    //   })
    //   return parseFloat(count).toFixed(4) || 0;
    // },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys1,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys1 = selectedRowKeys
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.name === 'Disabled User', // Column configuration not to be checked
            name: record.name
          }
        })
      }
    },
    rowSelectionDel() {
      return {
        selectedRowKeys: this.selectedRowKeysDel,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeysDel = selectedRowKeys
        },
        getCheckboxProps: (record) => ({
          props: {
            // disabled: record.name === 'Disabled User', // Column configuration not to be checked
            // name: record.name
          }
        })
      }
    },
    rowSelection1() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        // onSelect: this.onSelect,
        // onSelectAll: this.onSelectAll,
        getCheckboxProps: (record) => {
          return ({
            props: {
              disabled: Number(record.ApplyTotalQuantity) >= Number(record.TotalQuantity), // Column configuration not to be checked
              name: record.name
            }
          })
        }
      }
    }
  },
  mounted() {
    // this.$nextTick(() => {
    //   // 页面渲染完成后的回调
    //   this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
    this.tableHeight = document.body.clientHeight - 550

    //   console.log(document.body.clientHeight)
    //   console.log(this.time)
    //   this.getDataList()
    // })
  },
  mixins: [invoicemixin],
  methods: {
    getDecimalPlaces(num,c) {
      let count = c || 2;
      const decimalPart = String(num).match(/\.\d*/);
      return (decimalPart ? decimalPart[0].length - 1 : 0) <= count;
    },
    calcCount(){
      
    },
    handleRetainDecimal(){
      this.data2.forEach(item => {
        if(this.selectedRowKeys1.includes(item.detailcode)){
          // this.handleValChange(null, item, null, true)
          item.RetainDecimalCount = this.retainDecimalCount;
        }
      })
      this.retainDecimalVisible = false;
    },
    NumberFormats(value){
      if (!value && value != 0) {
        return ""
      }
      // 获取元素的文本内容
      const originalValue = parseFloat(Number(value).toFixed(2))
      // 使用toLocaleString方法将数字格式化为千分位表示
      let res = originalValue.toLocaleString()
      const match = res.match(/\.(\d+)/)
      if (match && match[1].length == 1) {
        // 如果找到匹配小数点后面的数字的长度加0   /'22.4'+0
        return res += '0'
      } else if (match && match[1].length == 0 || !match) {
        return res += '.00'
      } else {
        // 如果没有匹配小数部分长度，返回原数字。
        return res
      }
    },
    handlePushData() {
      let arr = [];
      // console.log(this.rowSelectionDel)
      this.delData.forEach(item => {
        if (this.selectedRowKeysDel.includes(item.detailcode)) {
          this.data2.push(item)
        } else {
          arr.push(item)
        }
      })
      let count = 0;
      this.delData = arr;
      this.data2.forEach(item => {
        this.handleValChange(null, item, null, true)
        count += Number(item.numskk)
      })
      this.Count = parseFloat(count).toFixed(4) || 0;
      this.selectDeleteVisible = false;
    },
    selectDeleteData() {
      // this.delData = []
      this.selectDeleteVisible = true;
    },
    retainDecimal(){
      if (this.selectedRowKeys1.length != 1) {
        this.$message.error('请选择一个货品！')
        return;
      }
      this.retainDecimalCount = this.data2.filter(item => item.detailcode === this.selectedRowKeys1[0])[0].RetainDecimalCount || 2
      this.retainDecimalVisible = true;
    },
    disCountModalShow() {
      if (this.selectedRowKeys1.length != 1) {
        this.$message.error('请选择一个货品！')
        return;
      }
      this.disCount = "";
      let flag = false;
      let flag1 = false;
      this.data2.forEach(item => {
        // if (item.detailcode.slice(0, -1) == this.selectedRowKeys1[0]) {
        //   flag = true;
        // }
        if (this.selectedRowKeys1.includes(item.detailcode)) {
          flag = ((item.kmoneys + "").replace(',', '') * 1) < 0
        }
      })
      if (flag) {
        this.$message.error('该单据为折扣单据')
        return;
      }

      this.disCountModalVisibly = true;
    },
    disCountOk() {

      let arr = JSON.parse(JSON.stringify(this.data2.filter(item => this.selectedRowKeys1.includes(item.detailcode))))
      console.log(arr[0],'266')
      if (this.disCount * 1 > arr[0].SumiInvRCost *1) {
        this.$message.error('折扣价不能大于原价')
        return;
      }
      arr.forEach(item => {
        item.kmoneys = this.disCount * -1;
        item.specification = ""
        item.compositionQuantity = ""
        item.quantity = ""
        item.origTaxSalePrice = ""
        item.markup = ""
        item.Openedquantity = ""
        item.Price = ""
        item.numskk = ""
        item.TM_Specs = ""
        item.TM_Unit = ""
        item.numskk = ""
        item.Price = ""
        // item.TM_Name = ""
        item.detailcode = item.detailcode + '_' + 1;
        item.disCountType = true;
      })
      this.data2.forEach((item, index) => {
        if (item.detailcode == arr[0].detailcode) {
          this.data2.splice(index, 1)
        }
      })
      this.data2.push(...arr);

      // this.data2.sort((a, b) => a.ventoryname - b.ventoryname);
      let seen = {}; // 用于存储已经出现的a属性值
      let index = 0; // 用于记录对象的位置
      this.data2.sort(function (obj1, obj2) {
        var a1 = obj1.ventoryname;
        var a2 = obj2.ventoryname;

        if (!seen.hasOwnProperty(a1)) {
          // 如果a1属性值在seen对象中不存在，则将其添加，并且将index递增
          seen[a1] = index;
          index++;
        }
        if (!seen.hasOwnProperty(a2)) {
          // 如果a2属性值在seen对象中不存在，则将其添加，并且将index递增
          seen[a2] = index;
          index++;
        }

        // 根据a属性值在seen对象中的索引来排序
        return seen[a1] - seen[a2];
      });



      this.disCountModalVisibly = false;
      console.log(this.data2)
      this.data2.forEach(item => {
        this.handleValChange(null, item, null, true)
      })
    },
    TypeChange(value) {
      if (
        value === '增值税普通发票' ||
        value === '增值税电子普通发票' ||
        value === '全电发票(普通发票)'
      ) {
        this.$refs.ruleForm.clearValidate(['zhanghu', 'kaihu', 'phone'])
      }
    },
    shouCusinfo() {
      // this.back();
      this.OutboundOrder = ''
      // this.$refs.SearchCusinfo.openForm(null, '选择开票客户')
      this.visible = false
      this.visiblees = false
      this.parentObj.$refs.SearchCusinfo.openForm(null, '选择开票客户')
    },
    openInfo(row) {
      this.visiblees = true
      this.loading = true
      this.$http
        .post(
          '/InvoiceManagement/Inv_InvoiceApplyMain/GetInvoicingInformation?id' +
          '=' +
          row.Id
        )
        .then((res) => {
          this.loading = false
          if (res.Success) {
            this.openForm(row.Id, row.TicketbuyerName, '详情', row, res.Data)
          } else {
            this.$message.error(res.Msg)
          }
        })
    },
    openForm(id, cCusName, title, userInfo, data, cancel) {
      this.entity = { DicKey: '' }
      this.start = 0
      this.tableWidth = 1580
      this.$nextTick(() => {
        this.tableWidth = 1580
      })

      this.details = false
      if (cancel == 'cancel') {
        this.cancel = true
      }
      if (title != '选择出库单') {
        this.Summary = true
        this.$set(this, 'tableWidth', 1520)
        this.$nextTick(() => {
          this.$set(this, 'tableWidth', 1520)
        })
      } else {
        this.Summary = false
      }
      this.userInfo = userInfo
      this.cusname = cCusName
      this.data2.forEach((item) => {
        item.markup = ''
        item.numskk = ''
      })
      this.Amount = 0
      this.name = this.cusname
      // this.columns2.forEach(item=>{

      // })
      this.$http
        .post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition', {
          PageIndex: 1,
          PageRows: 10000,
          SortField: 'Id',
          SortType: 'desc',
          Search: [{ Condition: 'cCusType', keyword: '1' }, { Condition: 'cCusName' }]
        })
        .then((res) => {
          if (res.Data.length > 0) {
            this.buyPeople = res.Data
            this.buyPeopleRead = res.Data
            // this.entity.DicKey =  res.Data[0].Id  ;
          } else {
            this.name = this.cusname
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })

      this.columns0 = this.columns2
      // let i =this.columns2.findIndex((item)=>item.dataIndex=='compositionQuantity');
      // this.columns2.splice(i,0, { title: '出库数量', dataIndex: 'quantity', width: '20%', align: 'right' },
      //     { title: '已开数量', dataIndex: 'Openedquantity', width: '20%', align: 'right' })
      this.cusid = id
      this.time = [
        this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)),
        this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
      ]
      this.getDataList()
      this.selectedRowKeys = []
      this.selectedRows = []
      this.pagination.current = 1
      this.title = title

      if (title == '详情') {
        // 详情页调。
        this.setTab = '1'
        this.parentId = userInfo.Id
        this.handleDetails(data)
      } else {
        this.visible = true
      }
    },
    changeViewDataList(){
      this.data2 = this.data2Old.filter(item=>item.Id==this.applyType);
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
      // if (JSON.parse(localStorage.getItem('SELECT_CHECK')) && JSON.parse(localStorage.getItem('SELECT_CHECK')).length > 0) {
      //   this.selectedRowKeys = JSON.parse(localStorage.getItem('SELECT_CHECK'))
      // }
    },
    handleCancel() {
      this.visiblity = false
    },
    changeTime(e) {
      this.timeDisabled = true
      this.time = []
      switch (e) {
        case 0:
          this.time[0] = this.timeFormat(
            new Date(new Date().getFullYear(), new Date().getMonth(), 1)
          )
          this.time[1] = this.timeFormat(
            new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)
          )
          break
        case 1:
          this.time[0] = this.timeFormat(
            new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1)
          )
          this.time[1] = this.timeFormat(
            new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)
          )
          break
        case 2:
          this.time[0] = this.timeFormat(
            new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1)
          )
          this.time[1] = this.timeFormat(
            new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)
          )
          break
        case 3:
          this.timeDisabled = false
          break
      }
    },
    //提交按钮
    showMergeSame() {
      this.IsMerge = false;
      this.mergeSameShow = true;
    },
    // 保存
    handleOk() {
      this.mergeSameShow = false;
      this.submitType = true;
      this.$message.info('提交中······')
      const Details = []
      this.data2.forEach((item) => {
        Details.push({
          OutboundOrder: item.code,
          InventoryCode: item.ventorycode,
          OutboundOrderDetails: item.detailcode,
          InventoryId: item.idinventory,
          InventoryName: item.ventoryname,
          InventoryPrice: item.InventoryPrice,
          Inventoryunit: item.compositionQuantity,
          Inventoryspec: item.specification,
          InvoicingQuantity: item.numskk,
          InvoicingPrice: item.Price,
          InvoicingAmount: Number(item.kmoneys.replace(/,/g, '')),
          InvoicingName: item.TM_Name,
          InvoicingCode: item.Taxproductcode,
          InvoicingId: item.TaxproductId,
          Invoicingunit: item.TM_Unit,
          Invoicingspec: item.TM_Specs,
          TaxRate: Number(item.TaxRate.replace('%', '')),
          TaxAmount: Number(item.TaxPrice.replace(/,/g, '')),
          Markup: item.markup,
          Batch: item.Batch,
          RetainDecimalCount: item.RetainDecimalCount
        })
      })
      const obj = {

        CusCode: this.userInfo.cCusCode,
        CusId: this.userInfo.Id,
        CusName: this.userInfo.cCusName,
        CusPhone: this.entity.phone,
        CusAddress: this.entity.phone,
        cCusEmail: this.entity.cCusEmail,
        TicketbuyerName: this.entity.DicKey,
        TicketbuyerId: this.entity.DicKey,
        Accbank: this.entity.kaihu,
        TaxRegcode: this.entity.zhanghu,
        PayeeUserId: '1',
        PayeeUserCode: '1',
        PayeeUserName: this.entity.shoupiaoren,
        PayeeUserPhone: this.entity.Phone,
        SellerName: this.entity.SellerName,
        SellerRegcode: this.entity.SellerRegcode,
        SellerAccbank: this.entity.SellerAccbank,
        SellerAddress: this.entity.SellerAddress,
        PayeeUserAddres: this.entity.shoupiaodizhi,
        Memo: this.entity.Remarks,
        Includingtaxinwords: Number(this.Amount) - Number(this.AmountOld),
        Amountincludingtax: Number(this.Amount) - Number(this.AmountOld),
        Remark: this.entity.Remark,
        Type: this.entity.Type,
        IsApply: 0,
        IsMerge: this.IsMerge,
        // TicketbuyerName:,//购买方姓名.
        // TicketbuyerId:,//购买方id
        Details
      }

      this.$http
        .post('/InvoiceManagement/Inv_InvoiceApplyMain/SaveInvoicingData', obj)
        .then((res) => {
          if (res.Success) {
            this.$message.success('提交成功')
            this.visible = false
            localStorage.removeItem('SELECT_CHECK')
            this.visiblity = false
            this.visiblees = false

            this.IsMerge = false;
            this.submitType = false;
            this.$parent.$parent.getDataList()
          } else {
            this.submitType = false;
            this.$message.error('提交失败')
          }
        }).catch(err => {
          this.$message.error(err);
          this.submitType = false;
        })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    onSelect(record, selected) {
      let select = JSON.parse(localStorage.getItem('SELECT_CHECK'))
      if (selected) {
        this.selectedRowKeys.push(record.OutboundOrder)
      } else {
        // 删除取消选择的
        select = select.filter((item) => item != record.OutboundOrder)
        this.selectedRowKeys = this.selectedRowKeys.filter(
          (item) => item != record.OutboundOrder
        )
      }
      // 如果选择无数据，就创建一个新的加进去。
      if (!JSON.parse(localStorage.getItem('SELECT_CHECK'))) {
        localStorage.setItem('SELECT_CHECK', JSON.stringify(this.selectedRowKeys))
      } else {
        // 反则push
        select.push(...this.selectedRowKeys)
        localStorage.removeItem('SELECT_CHECK')
        localStorage.setItem('SELECT_CHECK', JSON.stringify([...new Set(select)]))
      }
      this.submitDisabled = this.selectedRowKeys.length <= 0
    },
    onSelectAll(selected, selectedRows, changeRows) {
      const select = JSON.parse(localStorage.getItem('SELECT_CHECK'))
      if (selected) {
        changeRows.forEach((item) => {
          this.selectedRowKeys.push(item.OutboundOrder)
        })
      } else {
        // //删除取消选择的
        changeRows.forEach((item) => {
          select.forEach((item2, index) => {
            if (item2 == item.Id) {
              select.splice(index, 1)
            }
          })
        })
        this.selectedRowKeys = []
      }
      // 如果选择无数据，就创建一个新的加进去。
      if (!JSON.parse(localStorage.getItem('SELECT_CHECK'))) {
        localStorage.setItem('SELECT_CHECK', JSON.stringify(this.selectedRowKeys))
      } else {
        // 反则push
        select.push(...this.selectedRowKeys)
        localStorage.removeItem('SELECT_CHECK')
        localStorage.setItem('SELECT_CHECK', JSON.stringify([...new Set(select)]))
      }
      this.submitDisabled = this.selectedRowKeys.length <= 0
    },
    // 开票信息上一步
    shouorderforgoods() {
      this.OutboundOrder = ''
      this.visiblees = false
      this.time = []
      localStorage.removeItem('SELECT_CHECK')
      this.selectedRowKeys = []
      this.selectedRows = []
      this.visible = true
    },
    handleChangePrice() {
      // 批量修改
      this.data2.forEach((item) => {
        this.selectedRowKeys1.forEach((ite) => {
          if (item.detailcode == ite) {
            item.markup = this.changeMarkup
          }
        })
        this.handleValChange(null, item, null, true)
      })
      this.changeVisible = false
      this.changeMarkup = ''
    },
    handleSearch(value) {
      if (value == '') {
        return
      }
      //  this.buyPeople =  this.buyPeople.filter(data => (data.cCusName = data));
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.$http
          .post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition', {
            PageIndex: 1,
            PageRows: 25,
            SortField: 'Id',
            SortType: 'desc',
            Search: [
              { Condition: 'cCusType', keyword: '1' },
              { Condition: 'cCusName', keyword: value }
            ]
          })
          .then((res) => {
            this.buyPeople = res.Data
            this.buyPeopleRead = res.Data

            this.timer = null
          })
          .catch((err) => {
            this.timer = null
            this.$message.error(err)
          })
      }, 500)
    },
    handleChange(value) {
      this.buyPeopleRead.forEach((item) => {
        if (item.cCusName === value) {
          const kaihu = item.cCusBank == null && item.cCusAccount == null
          const phone = item.cCusAddress == null && item.cCusPhone == null
          // this.$set(this.entity, "zhanghu", this.userInfo.cCusTaxnumber)
          // this.$set(this.entity, "kaihu", kaihu ? "" : this.userInfo.cCusBank + this.userInfo.cCusAccount)
          // this.$set(this.entity, "phone", phone ? "" : (this.userInfo.cCusAddress + this.userInfo.cCusPhone))
          // this.$set(this.entity, "cCusEmail", (this.userInfo.cCusEmail))
          this.$set(this.entity, 'zhanghu', item.cCusTaxnumber)
          this.$set(this.entity, 'kaihu', kaihu ? '' : item.cCusBank)
          this.$set(this.entity, 'phone', phone ? '' : item.cCusAddress)
          this.$set(this.entity, 'cCusEmail', item.cCusEmail)
        }
      })
      this.name = value
      // console.log("<<<<<<<<"+value)
    },
    // throttle(fn, delay) {
    //   let timer = null;
    //   return function () {
    //     let context = this;
    //     let args = arguments;
    //     if (!timer) {
    //       timer = setTimeout(function () {
    //         fn.apply(context, args);
    //         timer = null;
    //       }, delay);
    //     }
    //   }
    // },
    SummarySubmission() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (
            !['增值税普通发票', '增值税电子普通发票', '全电发票(普通发票)'].includes(
              this.entity.Type
            )
          ) {
            if (this.entity.kaihu.split(' ').length !== 2 && this.entity.kaihu != '') {
              this.$message.error('请填充开户行及账号，格式：北京银行 110111111111')
              return
            }
            if (this.entity.phone.split(' ').length !== 2 && this.entity.phone != '') {
              this.$message.error('请填充地址及电话，格式：北京市 13888888888')
              return
            }
          }

          const reg = /^\d+(\.\d{0,2})?$/
          let flag = false
          let flag1 = false
          let flag2 = false


          this.data2.forEach((item) => {
            if(!item.disCountType){
              if (item.quantity - item.Openedquantity < item.numskk) {
                flag = true
              }
              if (item.numskk === '' || item.TM_Name === '' || item.Price === '') {
                flag1 = true
              }
              if (!this.getDecimalPlaces(item.Price, item.RetainDecimalCount)) {
                flag2 = true
              }
            }
          })
          if (
            !['增值税普通发票', '增值税电子普通发票', '全电发票(普通发票)'].includes(
              this.entity.Type
            )
          ) {
            const flag3 = this.data2.every((item) => {
              return item.TaxRate === this.data2[0].TaxRate
            })
            if (!flag3) {
              this.$message.warning('请检查列表内每个货物税率是否一致')
              return
            }
          }

          if (flag1) {
            this.$message.warning('信息请填写完毕')
            return
          }
          if (flag2) {
            this.$message.warning('请输入正确的价格，小数位数超过了您设置的上限！')
            return
          }
          if (!flag) {
            this.visiblity = true
          } else {
            // this.visiblity = true;
            this.$message.warning('数量不能大于出库-已开')
            return
          }
          // this.name = this.buyPeople.filter(item=>item.Id===this.entity.DicKey)[0].cCusName
          this.newArr = []
          this.Preview = []
          let arr = []
          const obj = {}
          arr = JSON.parse(JSON.stringify(this.data2))
          arr.forEach((item) => {
            if (!obj[item.TaxproductId]) {
              obj[item.TaxproductId] = []
              obj[item.TaxproductId].push(item)
            } else {
              obj[item.TaxproductId].push(item)
            }
          })
          for (const i in obj) {
            this.Preview.push(...obj[i])
            let OBJ = {}
            obj[i].forEach((item, index) => {
              if (index == 0) {
                OBJ = item
                OBJ.kmoneys = Number(OBJ.kmoneys)
                OBJ.TaxPrice = Number(OBJ.TaxPrice)
              } else {
                OBJ.numskk += item.numskk
                OBJ.kmoneys += Number(item.kmoneys)
                OBJ.TaxPrice += Number(item.TaxPrice)
              }
            })
            // if(Number.isInteger(OBJ.kmoneys)){
            //   console.log(123)
            //   OBJ.kmoneys += '.00';
            // }
            // if (Number.isInteger(OBJ.TaxPrice)) {
            //   OBJ.TaxPrice += '.00';
            // }
            this.newArr.push(OBJ)
          }
          // this.data2.forEach((item) => {
          //   // if (item.Price % 1 == 0) {
          //   //   item.Price = this.$options.filters.NumberFormatss(item.Price)
          //   //   // item.Price += '.00';
          //   // }
          //   if (Number(item.kmoneys.replace(/,/g, '')) % 1 == 0) {
          //     // item.kmoneys += '.00';
          //   }
          // })
          this.$nextTick(() => {
            this.$http
              .post('/Base_Manage/Base_Seller/GetDataList', {
                PageIndex: 1,
                PageRows: 1,
                SortField: 'Id',
                SortType: 'desc'
              })
              .then((res) => {
                this.entity.SellerName = res.Data[0].SellerName
                this.entity.SellerRegcode = res.Data[0].SellerRegcode
                this.entity.SellerAccbank = res.Data[0].SellerAccbank
                this.entity.SellerAddress = res.Data[0].SellerAddress
                this.$forceUpdate()
              })
              .catch((err) => {
                this.$message.error(err)
              })
          })
        } else {
          return false
        }
      })
    },
    async project(select, record) {
      record.TaxRate = (select ? select.TM_TaxRate : 0) + '%'

      this.$set(record, 'TM_Name', select ? select.Taxproductname : '')

      record.TaxproductId = select ? select.TaxproductId : ''
      record.Taxproductcode = select ? select.Taxproductcode : ''
      record.TM_Unit = select ? select.TM_Unit : ''

      // await this.handleValChange(null, record, null, true)

      this.$forceUpdate()
      this.Amount = 0
      this.AmountOld = 0
      let count = 0
      this.data2.forEach((item) => {
        count += Number(item.numskk)
        this.handleValChange(null, item, null, true)
      })
      this.Count = parseFloat(count).toFixed(4) || 0

    },
    setName(value, record) {
      record.TM_Name = value
    },
    // setMon(e) {
    //   // e.numskk = e.numskk.replace('.', '',)
    //   //   console.log(e.numskk)
    //   //   if (isNaN(e.numskk * 1)) {
    //   //     e.numskk = "";
    //   //     return;
    //   //   }

    //   const arr = e.numskk.split('.')
    //   if (arr.length > 1) {
    //     e.numskk = arr[0] + '.' + arr[1].slice(0, 2)
    //   }
    //   if (isNaN(e.numskk * 1)) {
    //     e.numskk = ''
    //   }
    //   let count = 0;
    //   this.delData = arr;
    //   this.data2.forEach(item => {
    //     this.handleValChange(null, item, null, true)
    //     count += Number(item.numskk)
    //   })
    //   this.Count = parseFloat(count).toFixed(4) || 0;
    // },
    //批量删除
    batchDeleteData() {
      this.Amount='0.00'
      let arr = [];
      this.data2.forEach((item, index) => {
        if (this.selectedRowKeys1.includes(item.detailcode)) {
          this.delData.push(item)
        } else {
          arr.push(item);
        }
      })
      this.data2 = arr;
      this.data2.forEach((ite) => {
        this.Amount = (
          (this.Amount * this.precision +
            (Number(ite.kmoneys.replace(/,/g, ''))
              ? Number(ite.kmoneys.replace(/,/g, ''))
              : 0) *
            this.precision) /
          this.precision
        ).toFixed(2)
      })
      this.data2.forEach(item => {
        this.handleValChange(null, item, null, true)
      })
      this.selectedRowKeys1=[];
      let count = 0;
      this.data2.forEach(item => {
        console.log(item, '111ss')
        count += Number(item.numskk)
      })
      this.Count = parseFloat(count).toFixed(4) || 0;
    },
    // 删除符合税率/名称
    delTaxRateFilter() {
      this.data2.filter(item => item.TaxRate.replace('%', '') == this.delTaxRate).forEach(item => {
        this.delData.push(item)
      })
      // console.log(...this.data2.filter(item => item.TaxRate.replace('%', '') == this.delTaxRate))
      this.data2 = this.data2.filter(item => item.TaxRate.replace('%', '') !== this.delTaxRate);
      // this.delData.push(...this.data2.filter(item => item.TaxRate.replace('%', '') == this.delTaxRate))
      // let flag= false;
      this.selectedRowKeys1 = [];
      // console.log(this.delData)
      this.Amount = 0
      this.AmountOld = 0;
      // this.data2.forEach((ite) => {
      //   this.Amount = (
      //     (this.Amount * this.precision +
      //       (Number(ite.kmoneys.replace(/,/g, ''))
      //         ? Number(ite.kmoneys.replace(/,/g, ''))
      //         : 0) *
      //       this.precision) /
      //     this.precision
      //   ).toFixed(2)


      // })
      let count = 0;
      this.data2.forEach(item => {
        console.log(item, '111ss')
        count += Number(item.numskk)
      })
      this.Count = parseFloat(count).toFixed(4) || 0;
      this.$emit('input', [...this.data2])
      this.$forceUpdate();
      this.data2.forEach(item => {
        this.handleValChange(null, item, null, true)
      })
      this.delTaxRateVisibty = false;
    },
    getDataList() {
      if (!this.cusid) return
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/InvoiceManagement/ST_RDRecord/GetCustomerRecords', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'Time',
          SortType: 'desc',
          Search: {
            Condition: 'CustomerId',
            Keyword: this.cusid,
            Code: this.OutboundOrder,
            StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '',
            EndTime: this.time[1] ? this.timeFormat(this.time[1]) : ''
          },
          ...this.filters
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data

          this.allData.push(...new Set(this.data))
          // 清空价格
         
          if (this.data) {

            this.data.forEach((item) => {
              item.CreateTime = this.timeFormat(item.CreateTime, 'YYYY-MM-DD')
              // item.TotalQuantity = item.toFixed(4)
              item.ApplyTotalQuantity = Number(item.ApplyTotalQuantity).toFixed('4')
            })
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
      this.$http
        .post('/InvoiceManagement/ST_RDRecord/GetCustomerRecordsTotal', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'Time',
          SortType: 'desc',
          Search: {
            Condition: 'CustomerId',
            Keyword: this.cusid,
            Code: this.OutboundOrder,
            StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '',
            EndTime: this.time[1] ? this.timeFormat(this.time[1]) : ''
          },
          ...this.filters
        })
        .then((resJson) => {
          this.PriceCount = resJson.Data.TotalMoney
        })
      this.delTaxRateVisibty = false;
    },
    // 批量修改价格
    batchChangePrice() {
      this.changeVisible = true
    },
    // 详情
    handleDetails(data, title) {
      this.data2 = []
      if (title) {
        this.info = '退票信息'
      } else {
        this.info = '开票信息'
      }

      this.entity = {}
      this.columns0 = this.columns3
      this.cusname = data.TicketbuyerName

      this.name = data.TicketbuyerName
      this.entity.DicKey = data.TicketbuyerName // 购货方
      this.entity.zhanghu = data.TaxRegcode // 税号
      this.entity.kaihu = data.Accbank // 开户行
      this.entity.phone = data.CusAddress
      this.entity.Remarks = data.Memo
      this.entity.shoupiaoren = data.PayeeUserName
      this.entity.Phone = data.PayeeUserPhone
      this.entity.shoupiaodizhi = data.PayeeUserAddres
      this.entity.Remark = data.Remark
      this.entity.cCusEmail = data.cCusEmail
      this.Amount = data.Amountincludingtax
      this.entity.Type = data.Type
      this.IsMerge = data.IsMerge
      this.AmountOld = 0;
      data.Details.forEach((item) => {
        const obj = {}
        obj.code = item.OutboundOrder
        obj.detailcode = item.OutboundOrderDetails
        obj.id = item.InventoryId
        obj.ventoryname = item.InventoryName
        obj.origTaxSalePrice = Number(item.InventoryPrice).toFixed(8)
        obj.compositionQuantity = item.Inventoryunit
        obj.specification = item.Inventoryspec
        obj.numskk = item.InvoicingQuantity
        obj.Price = Number(item.InvoicingPrice).toFixed(item.RetainDecimalCount || 2)
        obj.kmoneys = this.$options.filters.NumberFormats(item.InvoicingAmount)
        obj.ventorycode = item.InventoryCode
        obj.TM_Name = item.InvoicingName
        obj.TaxRate = item.TaxRate ? item.TaxRate + '%' : 0 + '%'
        obj.Allkmoneys = Number(item.TaxAmount) + Number(item.InvoicingAmount)
        obj.TaxPrice = Number(item.TaxAmount).toFixed(2)
        obj.markup = item.Markup
        this.data2.push(obj)
      })
      let count = 0;
      this.data2.forEach(item => {
        console.log(item, '111ss')
        count += Number(item.numskk)
      })
      this.Count = parseFloat(count).toFixed(4) || 0;
      this.details = true
      // this.visible = true
      this.visiblees = true
      this.$set(this, 'tableWidth', 1520)
      this.$nextTick(() => {
        this.$set(this, 'tableWidth', 1520)
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate()
        }
      })
      // let length = 0;
      // this.columns3.forEach(item=>{
      //   if(item.width){
      //     length+=item.width.replace('px','')*1;
      //   }
      // })
      // console.log(this.tableWidth,length)
    },
    // 详情取消
    closeDetails() {
      this.details = false
      this.visible = false
      this.visiblees = false
      this.data2 = []

      // this.$destroy();
      // this.parentObj.Details = false;

      this.columns0 = this.columns2
    },
    // 提交下一步
    handleSubmit() {
      // this.selectedRows = []
      // console.log(this.allData, this.selectedRowKeys)
      // const arr = []
      this.time = []
      this.selectedRowKeys1 = [];
      this.Count="0.00";
      this.OutboundOrder = ''
      this.delData = [];
      this.delTaxRate = "";
      this.Amount = "0.00";
      this.Amountyuan ='0.00';
      this.AmountOld = '0.00';
      // this.allData.forEach(item => {
      //   this.selectedRowKeys.forEach(it => {
      //     if (item.Id == it) {
      //       arr.push(item)
      //     }
      //   })
      // })
      // // 去重
      // this.selectedRows = arr.reduce((accumulator, current) => {
      //   const exists = accumulator.some(item => item.OutboundOrder === current.OutboundOrder)
      //   if (!exists) {
      //     accumulator.push(current)
      //   }
      //   return accumulator
      // }, [])
      if (!this.selectedRows.length) {
        return this.$message.warning('请选择出库单据')
      }
      this.loadingApply = true
      const arr = this.selectedRows.map((item) => {
        return item.Id
      })
      this.visible = false
      this.visiblees = true
      this.$http
        .post('/InvoiceManagement/ST_RDRecord/GetRdRecordByBillList', arr)
        .then(async (res) => {
          if (!res.Success) {
            this.loadingApply = false
          }
          if (res.Success) {
            this.$set(columns2, 'Price', 0)
            this.entity = res.Data
            this.$set(this.entity, 'DicKey', res.Data.TicketbuyerId)
            this.$http
              .post(
                '/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition',
                {
                  PageIndex: 1,
                  PageRows: 10000,
                  SortField: 'Id',
                  SortType: 'desc',
                  Search: [
                    { Condition: 'cCusType', keyword: '1' },
                    { Condition: 'cCusName' }
                  ]
                }
              )
              .then((res) => {
                if (res.Data.length > 0) {
                  this.buyPeople = res.Data
                  this.buyPeopleRead = res.Data
                  this.handleChange(this.entity.DicKey)
                  // this.entity.DicKey =  res.Data[0].Id  ;
                }
              })
              .catch((err) => {
                this.$message.error(err)
              })
              let arrList = [];
            for (var item of res.Data.Details) {
              this.$set(item, 'code', item.WsChukuCode)
              this.$set(item, 'detailcode', item.WsChukuDetailId)
              this.$set(item, 'ventorycode', item.cInvCode)
              this.$set(item, 'ventoryname', item.cInvName)

              this.$set(
                item,
                'specification',
                (item.Batch || '') + '  ' + (item.cInvStd || '')
              )
              this.$set(item, 'compositionQuantity', item.GroupName)
              this.$set(item, 'quantity', item.Quantity)

              this.$set(item, 'origTaxSaleAmount', item.umiInvRCost)
              // this.$set(item, 'Openedquantity', item.Number || 0)
              this.$set(item, 'Openedquantity', 0)
              this.$set(item, 'ReceivedQuantity', item.nums)

              // 开票名称
              // ---

              // 标准售价
              this.$set(
                item,
                'origTaxSalePrice',
                Number(item.InventoryPrice).toFixed(8) || 0
              )

              this.$set(item, 'markup', 100)
              this.$set(item, 'Price', Number(item.iInvRCost).toFixed(2))
              this.$set(item, 'numskk', item.Quantity)
              this.$set(item, 'kmoneys', item.SumiInvRCost)
              this.$set(item, 'TaxRate', '')
              this.$set(item, 'TaxPrice', '')
              this.$set(
                item,
                'TM_Specs',
                (item.Batch || '') + '  ' + (item.cInvStd || '')
              )
              // item.markup = 100
              // item.origTaxSalePrice = this.$options.filters.NumberFormats(item.origTaxSalePrice)
              this.$set(item, 'TM_UnitPrice', item.Price)

              // item.TM_UnitPrice = item.origTaxSalePrice
              arrList.push(item.ventorycode)
              
              
            }
           
            this.data2 = res.Data.Details
            // await this.getitemchange(arrList)
            this.loadingApply = false
            let count = 0;
            
            // this.data2.forEach(async (item) => {
            //   console.log(item, '111ss')
            //   count += Number(item.numskk)
              
            //   await 

            // })
            // res.Data.Details.forEach(item => {
            this.Amount = 0
            this.data2.forEach((ite) => {

              this.Amount = (
                (this.Amount * this.precision +
                  (Number(ite.kmoneys.replace(/,/g, ''))
                    ? Number(ite.kmoneys.replace(/,/g, ''))
                    : 0) *
                  this.precision) /
                this.precision
              ).toFixed(2)
              this.handleValChange(null, item, null, true)

            })
            this.Count = parseFloat(count).toFixed(4) || 0;

            // })
          }
        })
       
      return

      this.data2 = this.selectedRows
      this.$set(columns2, 'Price', 0)
      console.log(123)
      this.$nextTick(() => {
        this.loadingApply = true
        console.log(123)
        const arr = []
        this.data2.forEach((item) => {
          arr.push(item.Id)
        })
        this.$http
          .post('/InvoiceManagement/ST_RDRecord_b/DeliveryNoteReceipt', {
            Search: {
              OutboundOrders: arr
            }
          })
          .then((res) => {
            this.$http
              .post('/InvoiceManagement/ST_RDRecord_b/GetRDRecordList', {
                PageIndex: 1,
                PageRows: 10000,
                SortField: 'Code',
                SortType: 'desc',
                Search: {
                  OutboundOrders: arr
                }
              })
              .then((resJson) => {
                const arr = []

                resJson.Data.forEach((item, index) => {
                  arr.push(
                    this.$http
                      .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetRDRecordList', {
                        PageIndex: 1,
                        PageRows: 20,
                        SortField: 'TaxproductId',
                        SortType: 'desc',
                        Search: {
                          Keyword: item.ventorycode
                        }
                      })
                      .then((resJson) => {
                        console.log(resJson, item)
                        item.TaxRate =
                          (resJson.Data[0].TM_TaxRate ? resJson.Data[0].TM_TaxRate : 0) +
                          '%'
                        item.TaxPrice = Number(0).toFixed(2)
                        item.kmoneys = Number(0).toFixed(2)
                        this.$set(item, 'TM_Name', resJson.Data[0].Taxproductname)
                        // item.TM_Name = resJson.Data[0].Taxproductname;
                        item.TaxproductId = resJson.Data[0].TaxproductId
                        item.Taxproductcode = resJson.Data[0].Taxproductcode
                        item.TM_Unit = resJson.Data[0].TM_Unit
                        item.TM_Specs = resJson.Data[0].TM_Specs
                        item.origTaxSalePrice = this.$options.filters.NumberFormats(
                          resJson.Data[0].TM_UnitPrice
                        )
                        item.TM_UnitPrice = resJson.Data[0].TM_UnitPrice
                        item.markup = 100
                        item.numskk = item.Unopenedquantity
                        this.handleValChange(null, item, null, true)
                      })
                      .catch((err) => {
                        // this.$message.error(err)
                      })
                  )
                })

                Promise.all(arr).then(() => {
                  this.loadingApply = false
                  this.data2 = resJson.Data
                  // 清空合计
                  this.Amount = 0
                  // 计算合计
                  this.data2.forEach((ite) => {
                    // 精度
                    console.log(ite)
                    // console.log(this.Amount, Number(ite.kmoneys.replace(/,/g, '')), Number(ite.TaxPrice.replace(/,/g, '')))
                    this.Amount = (
                      (this.Amount * this.precision +
                        (Number(ite.kmoneys.replace(/,/g, ''))
                          ? Number(ite.kmoneys.replace(/,/g, ''))
                          : 0) *
                        this.precision) /
                      this.precision
                    ).toFixed(2)
                    // this.Amount = this.Amount  + Number(ite.kmoneys.replace(',', '')) + Number(ite.TaxPrice.replace(',', '')) ;
                  })

                  this.$forceUpdate()
                })
              })
          })
      })

      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()
        console.log(this.userInfo, 'userInfo??????????????')

        const kaihu = this.userInfo.cCusBank == null && this.userInfo.cCusAccount == null
        const phone =
          this.userInfo.cCusAddress == null && this.userInfo.cCusPhone == null
        this.$set(this.entity, 'DicKey', this.userInfo.cCusName)
        this.$set(this.entity, 'zhanghu', this.userInfo.cCusTaxnumber)
        this.$set(
          this.entity,
          'kaihu',
          kaihu ? '' : this.userInfo.cCusBank + this.userInfo.cCusAccount
        )
        this.$set(
          this.entity,
          'phone',
          phone ? '' : this.userInfo.cCusAddress + this.userInfo.cCusPhone
        )
        this.$set(this.entity, 'cCusEmail', this.userInfo.cCusEmail)
      })
    },
    handleDelete(items) {
      var thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          items.forEach((element) => {
            var index = thisObj.data2.indexOf(element)
            thisObj.data2.splice(index, 1)
            this.delData.push(items[index]);
            var keyIndex = thisObj.selectedRowKeys.indexOf(element.code)
            thisObj.selectedRowKeys.splice(keyIndex, 1)
          })
          this.Amount = 0
          this.data2.forEach((ite) => {
            this.Amount = (
              (this.Amount * this.precision +
                (Number(ite.kmoneys.replace(/,/g, ''))
                  ? Number(ite.kmoneys.replace(/,/g, ''))
                  : 0) *
                this.precision) /
              this.precision
            ).toFixed(2)
          })
          thisObj.$emit('input', [...thisObj.data2])
          resolve()
        })
      })
    },
    // 价格框输入
    handlePriceChange(val, item) {
      // const reg = /^\d+(\.\d{0,2})?$/
      if (this.getDecimalPlaces(item.Price, item.RetainDecimalCount)) {
        // item.Price = Number(val.target.value)
      } else {
        this.$message.warning('请输入正确的价格，最多' + (item.RetainDecimalCount ? item.RetainDecimalCount:2) +'位小数')
        return
      }
      item.markup =
        (Number(val.target.value) / item.TM_UnitPrice) * 100
          ? ((Number(val.target.value) / item.TM_UnitPrice) * 100).toFixed(4)
          : 0
      // item.markup = ((Number(val.target.value) - this.$options.filters.NumberFormats(item.Price / (1 + item.TaxRate.replace('%', '') / 100) * item.TaxRate.replace('%', '') / 100)) / item.TM_UnitPrice * 100) ? ((Number(val.target.value) - this.$options.filters.NumberFormats(item.Price / (1 + item.TaxRate.replace('%', '') / 100) * item.TaxRate.replace('%', '') / 100)) / item.TM_UnitPrice * 100).toFixed(4) : 0
      this.calcAmount();
      item.Price = val.target.value

      // this.handleValChange(null, item)
    },
    // 精度丢失计算
    actionOperationResult(val1, val2, val3) {
      const p = this.actionOperation(val1, val2, val3)
      return (val1 * p * (val2 * p) * (val3 * p || 1)) / (p * p * (val3 ? p : 1))
    },
    actionOperation(val1, val2, val3) {
      const len1 = val1.toString().length - val1.toString().indexOf('.') - 1
      const len2 = val2.toString().length - val2.toString().indexOf('.') - 1
      let p = 0
      if (val3) {
        const len3 = val3.toString().length - val3.toString().indexOf('.') - 1
        p = Math.max(len1, len2, len3)
      } else {
        p = Math.max(len1, len2)
      }

      // 避免最终求出结果的长度大于最大长度的时候导致精度丢失 开启下面
      // p += p - Math.min(len1, len2);
      return Math.pow(10, p)
    },
    async handleValChange(val, item, index, f) {
      console.log(item, '1');
      let kmoneys = 0
      if (item.Price && item.numskk) {
        // if ((item.numskk + '').split('.').length > 1) {
        //   if ((item.numskk + '').split('.')[1].length > 2) {
        //     return
        //   }
        // }
        if (item.markup < 0) {
          item.markup = 0
        }
        if (item.numskk < 0) {
          item.numskk = 0
        }
        if (f) {
          console.log(item.markup, '1111')
          console.log(item.TM_UnitPrice, '2222222')
          console.log(item.Price, '2222222')
          item.Price =
            (item.markup * item.TM_UnitPrice) / 100
              ? ((item.markup * item.TM_UnitPrice) / 100).toFixed(item.RetainDecimalCount || 2)
              : 0
          // item.Price = ((item.markup * item.TM_UnitPrice / 100 * (1 + Number(item.TaxRate.replace('%', '')) / 100))) ? ((item.markup * item.TM_UnitPrice / 100 * (1 + Number(item.TaxRate.replace('%', '')) / 100))).toFixed(8) : 0
          item.cleanPrice =
            ((item.markup * item.TM_UnitPrice) / 100) *
              (Number(item.TaxRate.replace('%', '')) / 100)
              ? (
                ((item.markup * item.TM_UnitPrice) / 100) *
                (Number(item.TaxRate.replace('%', '')) / 100)
              ).toFixed(8)
              : 0
        }

        let cleanPrice = 0
        // 计算金额
        if (item.Price && Number(item.numskk)) {
          kmoneys = this.actionOperationResult(item.Price, Number(item.numskk)).toFixed(2)
          cleanPrice = this.actionOperationResult(item.Price, Number(item.numskk)).toFixed(
            2
          )
        }
      } else {
        kmoneys = (item.kmoneys + '').replace(',', '') * 1;
        // kmoneys = item.kmoneys;
      }
      // 计算税额
      if (kmoneys && !item.disCountType) {
        // console.log(item.markup, item.TM_UnitPrice, item.TaxRate.replace('%', ''), 'sadfojosadigjoisdjagoisadj')

        // item.TaxPrice = ((item.markup * item.TM_UnitPrice / 100 * (Number(item.TaxRate.replace('%', '')) / 100)))* item.markup/100 *   Number(item.numskk)? this.$options.filters.NumberFormats(((item.markup * item.TM_UnitPrice / 100 * (Number(item.TaxRate.replace('%', '')) / 100))) * item.markup / 100 * Number(item.numskk)) : '0.00'
        // Number(item.TaxRate.substr(0, item.TaxRate.length - 1))

        const TaxRate = Number(item.TaxRate.replace('%', ''))

        item.TaxPrice =
          (((Number(item.numskk) || 0) * (Number(item.Price) || 0)) / (1 + TaxRate)) *
          TaxRate || '0.0000'

        item.TaxPrice = Number(item.TaxPrice).toFixed(2)
        // item.TaxPrice = this.$options.filters.NumberFormats(Number(cleanPrice)*((item.TaxRate).replace("%", "") / 100));

        // item.Allkmoneys = (Number(kmoneys) + Number(item.TaxPrice.replace(/,/g, ''))).toFixed(2)
      } else {
        console.log(item.kmoneys, 'false123')
        const TaxRate = Number(item.TaxRate.replace('%', ''))
        item.TaxPrice = this.str2Num(item.kmoneys) / (1 + TaxRate) * TaxRate
        item.TaxPrice = Number(item.TaxPrice).toFixed(2)
      }
      item.kmoneys = this.$options.filters.NumberFormats(kmoneys)

      // 清空合计
      // this.Amount = 0
      // this.AmountOld = 0
      // 计算合计
      // this.data2.forEach((ite) => {
      // 精度
      // console.log(this.Amount, Number(ite.kmoneys.replace(/,/g, '')), Number(ite.TaxPrice.replace(/,/g, '')))
      // if (item.kmoneys) {
      item.kmoneys = item.kmoneys + '';
      this.Amount = (
        (this.Amount * this.precision +
          (Number(item.kmoneys.replace(/,/g, '')) > 0
            ? Number(item.kmoneys.replace(/,/g, ''))
            : 0) *
          this.precision) /
        this.precision
      ).toFixed(2)
      if (Number(item.kmoneys.replace(/,/g, '')) * 1 < 0) {
        this.AmountOld -= Number(item.kmoneys.replace(/,/g, '')) * 1;
        console.log(this.AmountOld)
      }
      console.log(Number(item.kmoneys.replace(/,/g, '')))
      // }
      this.Amountyuan = this.Amount - this.AmountOld
      // let count = 0;
      // this.data2.forEach(item => {
      //   console.log(item, '111ss')
      //   count += Number(item.numskk)
      // })
      // this.Count = parseFloat(count).toFixed(4) || 0;
      // this.Amount = this.Amount  + Number(ite.kmoneys.replace(',', '')) + Number(ite.TaxPrice.replace(',', '')) ;
      // })
      this.$emit('input', [...this.data2])
      this.$forceUpdate()
    },
    
    handlerpreviewTable(id) {
      this.previewTable = true;
      this.applyType = 0;
      this.loadingPreview = true;
      this.$http
        .post('/InvoiceManagement/ST_RDRecord/GetBillInfo', {id})
        .then(async (res) => {
          if (!res.Success) {
            this.loadingApply = false
          }
          if (res.Success) {
            let data = res.Data;
            this.columnsPreview = data.columns
            this.columnsPreview.forEach(item=>{
              item.width="150px";
              item.align="center";
            })
            this.data2 = data.datalist
            this.data2Old = JSON.parse(JSON.stringify(data.datalist))
            // console.log(this.data2Old,'olddata');
            // this.data2.forEach(item=>{
            //   item.SumiInvRCost = this.$options.filters.NumberFormats(item.SumiInvRCost)
            //   item.iInvRCost = this.$options.filters.NumberFormats(item.iInvRCost)
              
            //   if (item.ManufactureDate){
            //     if (item.ManufactureDate.includes('/')) {
            //       let arr = item.ManufactureDate.slice(0, 10).split('/');
            //       item.ManufactureDate = arr[2] + '-' + arr[0] + '-' + arr[1]
            //     }
            //   }
            // })
            this.data2 = this.data2.filter(item => item.Id == this.applyType);
            this.loadingPreview = false;
           
          }
        })
    },
    callback(e) {
      this.setTab = e
      if (e == '1') {
      } else if (e == '2') {
        this.$http
          .post('/InvoiceManagement/v_applicationsummary/GetDataList', {
            PageIndex: 1,
            PageRows: 10000,
            SortField: 'code',
            SortType: 'desc',
            Search: {
              Condition: 'ParentId',
              Keyword: this.parentId
            }
          })
          .then((res) => {
            res.Data.forEach((item) => {
              // item.InvoicingPrice=this.$options.filters.NumberFormatss(item.InvoicingPrice)
              item.InvoicingAmount = this.$options.filters.NumberFormats(
                item.InvoicingAmount
              )
              item.TaxAmount = this.$options.filters.NumberFormats(item.TaxAmount)
              item.InvoicingQuantity = this.$options.filters.NumberFormat(
                item.InvoicingQuantity
              )
            })
            this.SummaryData = res.Data
          })
      } else if (e == '3') {
        this.$http
          .post('/InvoiceManagement/v_applicationsummary/GetDataList', {
            PageIndex: 1,
            PageRows: 10000,
            SortField: 'code',
            SortType: 'desc',
            Search: {
              Condition: 'ParentId',
              Keyword: this.parentId
            }
          })
          .then((res) => {
            res.Data.forEach((item) => {
              // item.InvoicingPrice=this.$options.filters.NumberFormatss(item.InvoicingPrice)
              item.InvoicingAmount = this.$options.filters.NumberFormats(
                item.InvoicingAmount
              )
              item.TaxAmount = this.$options.filters.NumberFormats(item.TaxAmount)
              item.InvoicingQuantity = this.$options.filters.NumberFormat(
                item.InvoicingQuantity
              )
            })
            this.InvoiceData = res.Data
          })
      } else if (e == '4') {
        this.$http
          .post('/InvoiceManagement/v_applicationsummary/GetDataList', {
            PageIndex: 1,
            PageRows: 10000,
            SortField: 'code',
            SortType: 'desc',
            Search: {
              Condition: 'ParentId',
              Keyword: this.parentId
            }
          })
          .then((res) => {
            res.Data.forEach((item) => {
              // item.InvoicingPrice=this.$options.filters.NumberFormatss(item.InvoicingPrice)
              item.InvoicingAmount = this.$options.filters.NumberFormats(
                item.InvoicingAmount
              )
              item.TaxAmount = this.$options.filters.NumberFormats(item.TaxAmount)
              item.InvoicingQuantity = this.$options.filters.NumberFormat(
                item.InvoicingQuantity
              )
            })
            this.OutboundData = res.Data
          })
      } else if (e == '5') {
        this.$http
          .post('/InvoiceManagement/v_applicationsummary/GetDataList', {
            PageIndex: 1,
            PageRows: 10000,
            SortField: 'code',
            SortType: 'desc',
            Search: {
              Condition: 'ParentId',
              Keyword: this.parentId
            }
          })
          .then((res) => {
            res.Data.forEach((item) => {
              // item.InvoicingPrice=this.$options.filters.NumberFormatss(item.InvoicingPrice)
              item.InvoicingAmount = this.$options.filters.NumberFormats(
                item.InvoicingAmount
              )
              item.TaxAmount = this.$options.filters.NumberFormats(item.TaxAmount)
              item.InvoicingQuantity = this.$options.filters.NumberFormat(
                item.InvoicingQuantity
              )
            })
            this.OrderData = res.Data
          })
      } else if (e == '6') {
        this.$http
          .post('/InvoiceManagement/v_applicationsummary/GetDataList', {
            PageIndex: 1,
            PageRows: 10000,
            SortField: 'code',
            SortType: 'desc',
            Search: {
              Condition: 'ParentId',
              Keyword: this.parentId
            }
          })
          .then((res) => {
            res.Data.forEach((item) => {
              // item.InvoicingPrice=this.$options.filters.NumberFormatss(item.InvoicingPrice)
              item.InvoicingAmount = this.$options.filters.NumberFormats(
                item.InvoicingAmount
              )
              item.TaxAmount = this.$options.filters.NumberFormats(item.TaxAmount)
              item.InvoicingQuantity = this.$options.filters.NumberFormat(
                item.InvoicingQuantity
              )
            })
            this.SalesData = res.Data
          })
      }
    },
    async getitemchange(arr) {
      // console.log(item, 'itemitemitemitem')
      // await this.$http
      //   .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetRDRecordListBatch', arr)
      //   .then(async (resJson) => {
      //     // this.data2.forEach(async (item)=>{
      //     //   let obj = resJson.Data.filter(ite => ite.cInvCode == item.ventorycode)[0]
      //     //   if (item.ventorycode == obj.cInvCode){
      //     //     item.TaxRate = (obj ? obj.TM_TaxRate : 0) + '%'
      //     //     this.$set(
      //     //       item,
      //     //       'TM_Name',
      //     //       obj ? obj.Taxproductname : ''
      //     //     )
      //     //     item.TaxproductId = obj ? obj.TaxproductId : ''
      //     //     item.Taxproductcode = obj ? obj.Taxproductcode : ''
      //     //     item.TM_Unit = obj ? obj.TM_Unit : ''

      //     //     console.log(JSON.parse(JSON.stringify(item)), 'jsonjsonjsonjsonjson')
      //     //     // await this.handleValChange(null, it, null, true)
      //     //   }
      //     // })
          
      //   })
    },
    timeFormat(val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD')
    },
    str2Num(val) {
      if (!val) {
        return 0
      }
      if (typeof val === 'number') {
        return val
      }
      let str = val.replace(/,/g, '')
      return Number(str)
    },
    taxrage(item) {
      if (!item.TaxRate) {
        return 0
      }
      if (typeof item.TaxRate === 'string') {
        return Number(item.TaxRate.replace('%', ''))
      } else {
        return item.TaxRate
      }
    },
  }
}
</script>
<style scoped>
/deep/ .ant-table-small>.ant-table-content>.ant-table-scroll>.ant-table-header>table>.ant-table-thead>tr>th {
  text-align: center !important;
}

.my-switch.ant-switch {
  min-width: 190px;
  height: 50px;
}

/deep/.my-switch .ant-switch-inner {
  font-size: 20px !important;
}

.my-switch.ant-switch.ant-switch::after {
  width: 30px;
  height: 30px;
  top: 10px;
}
</style>
